Resolved Autosize font-size by width AND height

Discussion in 'Mac Programming' started by DennisBlah, Jun 8, 2015.

  1. DennisBlah, Jun 8, 2015
    Last edited: Jun 8, 2015

    DennisBlah macrumors 6502

    DennisBlah

    Joined:
    Dec 5, 2013
    Location:
    The Netherlands
    #1
    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)
     
  2. DennisBlah thread starter macrumors 6502

    DennisBlah

    Joined:
    Dec 5, 2013
    Location:
    The Netherlands
    #2
    Please close thread as I can't set it to resolved anymore with this new layout?
    Oops found it, please delete this reply:rolleyes:
     

Share This Page