NSTextView或NSTextField是否自动调整边界/帧的大小? [英] NSTextView or NSTextField automatically resize bounds / frame?

查看:85
本文介绍了NSTextView或NSTextField是否自动调整边界/帧的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 NSTextView 或 NSTextField 来显示我通过 textField.stringValue = [dictionary objectForKey:@"info"];

I'm trying to use either an NSTextView or NSTextField which displays text that I am adding via textField.stringValue = [dictionary objectForKey:@"info"];

问题是我需要文本区域的边界/框架垂直调整大小以显示所有文本.文本从几个单词(一行)到一两个段落不等.

The problem is I need the bounds / frame of the text area to vertically re-size to show all of the text. The text varies from a couple of words (1 line) to a paragraph or two.

当我尝试 [textField sizeToFit];

它将整个东西的大小缩小到单行,这太荒谬了(并且无法查看).我需要它根据当前窗口的宽度自动调整其宽度,并根据该高度调整其高度,以继续显示所有文本.

It re-sizes the whole thing down to a single line which is absurdly too long (and goes off view). I need it to auto re-size its width according to the current window width and based off of that re-size its height to keep showing all the text.

关于尝试或指导的任何想法?这适用于 OSX 而非 iOS.

Any ideas on what to try or direction? This is for OSX no iOS.

(此TextField或TextView将在基于基于视图的-NSTableView中使用.因此,我最终试图使我的表根据该文本框动态调整其行高.)

(This TextField or TextView is going in a View Based - NSTableView. So I am eventually trying to get my tables to dynamically re-size their row height based on that text box.)

推荐答案

我需要在当前项目中执行与此类似的操作.诀窍是在 NSString 上使用 sizeWithFont 方法.这将返回一个 CGSize ,然后您可以使用它构建一个正确大小的框架以适合您的文本.

I needed to do something similar to this on my current project. The trick is to use the sizeWithFont method on NSString. This will return a CGSize which you can then use to build a correctly sized frame to fit your text.

-(void) setCaption: (NSString*) text size:(CGSize) maxSize
{
    [self.label setText:text];
    UIFont* font=[UIFont systemFontOfSize: [UIFont systemFontSize]]
    [[self label] setFont:font];

    CGSize size=[text sizeWithFont:font constrainedToSize:maxSize];  
    label.frame = CGRectMake(0, 0, size.width, size.height);
}

如果您无权访问该视图,则可以将其汇总到类帮助器方法中.

If you don't have access to the view, then you could roll this up into a Class helper method.

这篇关于NSTextView或NSTextField是否自动调整边界/帧的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆