I have been trying to get a multi-line NSTextField
to lay out automatically using preferredMaxLayoutWidth
. I can’t figure out why this doesn’t work.
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textField = NSTextField()
textField.cell!.usesSingleLineMode = false
textField.cell!.wraps = true
textField.cell!.lineBreakMode = .byCharWrapping
view.addSubview(textField)
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textField.topAnchor.constraintEqual(to: view.topAnchor),
textField.leadingAnchor.constraintEqual(to: view.leadingAnchor),
textField.widthAnchor.constraintEqual(toConstant: 20)
])
textField.preferredMaxLayoutWidth = 20
textField.stringValue = "abcdefghijklmnopqrstuvwxyz"
view.needsLayout = true
view.layoutSubtreeIfNeeded()
print("Intrinsic content size: \(textField.intrinsicContentSize)")
print("Fitting size: \(textField.fittingSize)")
}
}
This prints:
Intrinsic content size: (-1.0, 21.0)
Fitting size: (20.0, 21.0)
(21.0 is the size for a single line.)