Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change NSTextField font size to fit

Is there anything like the UILabel's adjustsFontSizeToFitWidth that can be used with a NSTextField?

like image 957
Fernando Valente Avatar asked Dec 21 '10 19:12

Fernando Valente


2 Answers

Swift 4 solution:

It will resize one by one until it fits, or until minimumFontSize = 3.

    let minimumFontSize = 3

    var sizeNotOkay = true
    var attempt = 0

    while sizeNotOkay || attempt < 15 { // will try 15 times maximun
        let expansionRect = textField.expansionFrame(withFrame: textField.frame)

        let truncated = !NSEqualRects(NSRect.zero, expansionRect)

        if truncated {
            if let actualFontSize : CGFloat = textField.font?.fontDescriptor.object(forKey: NSFontDescriptor.AttributeName.size) as? CGFloat {
                textField.font = NSFont.systemFont(ofSize: actualFontSize - 1)

                if actualFontSize < minimumFontSize {
                    break
                }
            }
        } else {
            sizeNotOkay = false
        }

        attempt += 1
    }
like image 87
ricardo Avatar answered Oct 15 '22 01:10

ricardo


In short: no. You have to do some brute force work to determine a string's -sizeWithAttributes: -boundingRectWithSize:options:attributes: with a given font size (set as an NSFont for NSFontAttributeName).

I'd start with a standard system font size and work down or up from there, depending on whether it's smaller or larger than the desired rectangle.

like image 30
Joshua Nozzi Avatar answered Oct 15 '22 02:10

Joshua Nozzi