问题
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.
When I try [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.
Any ideas on what to try or direction? This is for OSX no iOS.
(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.)
回答1:
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.
来源:https://stackoverflow.com/questions/12078390/nstextview-or-nstextfield-automatically-resize-bounds-frame