Change NSTextField font size to fit

杀马特。学长 韩版系。学妹 提交于 2019-12-18 06:22:19

问题


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


回答1:


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.




回答2:


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
    }


来源:https://stackoverflow.com/questions/4503307/change-nstextfield-font-size-to-fit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!