Change the font size of NSTextField to fit

Is there anything like UILabel adjustsFontSizeToFitWidththat can be used with an NSTextField?

+3
source share
2 answers

In short: no. You have to do some hard work to determine the line - sizeWithAttributes: - boundingRectWithSize: options: attributes: with the given font size (set as NSFont for NSFontAttributeName).

I would start with the standard size of the system font and work down or up from there, depending on whether it is smaller or larger than the desired rectangle.

+1
source

Swift 4 solution:

, , = 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
    }
0

All Articles