UIKit's [NSString sizeWithFont:constrainedToSize:] in AppKit

前端 未结 6 1294
旧巷少年郎
旧巷少年郎 2021-01-02 22:47

Is there any equivalent method in AppKit (for Cocoa on Mac OS X) that does the same thing as UIKit\'s [NSString sizeWithFont:constrainedToSize:]?

If not

6条回答
  •  不知归路
    2021-01-02 22:57

    Here is a more complete example of how you can do this using boundingRectWithSize.

    // get the text field
    NSTextField* field = (NSTextField*)view;
    
    // create the new font for the text field
    NSFont* newFont = [NSFont fontWithName:@"Trebuchet MS" size:11.0];
    
    // set the font on the text field
    [field setFont:newFont];
    
    // calculate the size the textfield needs to be in order to display the text properly
    NSString* text      = field.stringValue;
    NSInteger maxWidth  = field.frame.size.width;
    NSInteger maxHeight = 20000;
    CGSize constraint   = CGSizeMake(maxWidth, maxHeight);
    NSDictionary* attrs = [NSDictionary dictionaryWithObjectsAndKeys:NSFontAttributeName,newFont, nil];
    NSRect newBounds    = [text boundingRectWithSize:constraint
                                             options:NSLineBreakByWordWrapping | NSStringDrawingUsesLineFragmentOrigin
                                          attributes:attrs];
    
    // set the size of the text field to the calculated size
    field.frame = NSMakeRect(field.frame.origin.x, field.frame.origin.y, field.frame.size.width, newBounds.size.height);
    

    Of course, for additional info, take a look at the Apple documentation:

    • Options for the attributes dictionary
    • boundingRectWithSize

提交回复
热议问题