Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...