0

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

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

当我尝试[textField sizeToFit];

它将整个事情重新调整为一条太长的单行(并且消失了)。我需要它根据当前窗口宽度自动重新调整其宽度,并根据该重新调整其高度来继续显示所有文本。

关于尝试什么或方向的任何想法?这适用于没有 iOS 的 OSX。

(此 TextField 或 TextView 将进入基于视图- NSTableView。所以我最终试图让我的表格根据该文本框动态调整其行高。)

4

1 回答 1

0

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.

于 2012-08-22T17:37:11.657 回答