NSString boundingRectWithSize slightly underestimating the correct height - why?

前端 未结 4 1039
时光说笑
时光说笑 2020-12-16 14:49

I\'m attempting to resize a text field / view automatically depending on its current width. In other words I want the width to stay constant but resize the height according

4条回答
  •  不思量自难忘°
    2020-12-16 15:47

    I found that NSString#boundingRectWithSize is never exactly correct, the only thing that seems to work well is the one described here: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html

    class func sizeForString(_ text : String, withFont font: NSFont, inWidth maxWidth: CGFloat) -> NSSize {
        let textStorage = NSTextStorage(string: text)
        let textContainer = NSTextContainer(containerSize: NSSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude))
        let layoutManager = NSLayoutManager()
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)
        textStorage.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, textStorage.length))
    textContainer.lineFragmentPadding = 0
        layoutManager.glyphRange(for: textContainer)
        return layoutManager.usedRect(for: textContainer).size
     }
    

提交回复
热议问题