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
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
}