Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

DennisBlah

macrumors 6502
Original poster
Dec 5, 2013
485
2
The Netherlands
Hi all,

I'm having difficulties with autoLayout.
I got fixed heights for containers, but dynamic width's for some NSTextFields.

How can I auto-size the font-size of my textfields content?
This must be done by the width, but may not exceed the height.

Does anyone have a good working subclass for this?

please advice!

--------

After some googling I found a few functions, but none was successful.
Combining them solved my issue!

Code:
- (void) prepareTextField:(NSTextField *)field minSize:(float)minSize maxSize:(float)maxSize {
    float fontSize = maxSize;
    for(int a=maxSize; a>=minSize; a--) {
        NSDictionary *attributes = [[NSDictionaryalloc] initWithObjectsAndKeys:[NSFontfontWithName:[[field font] fontName] size:a], NSFontAttributeName, nil];
        NSSize sizes = [field.stringValue sizeWithAttributes:attributes];
        if (sizes.width < field.frame.size.width && sizes.height < field.frame.size.height)
            break;
        fontSize--;
    }
    [field setFont:[NSFont systemFontOfSize: fontSize]];
}

//Usage: [self prepareTextField:<IBOutlet of textfield> minSize:<min. fontSize> maxSize:<max. fontSize>];
(This is not resizing the rectangle for the textfield! Only sets fontSize when fonts width AND height is smaller than the rectangle)
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.