Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

objective c - NSTextView or NSTextField automatically resize bounds / frame?

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...