In iOS
we can control the number of lines in Storyboard > Attributes > Number of lines
. We can put 0 to make an undetermined number and then the label adapts to the content.
Also programatically: label1.numberOfLines = 0
I do not see an equivalent in macOS
. I can option enter manually in Storyboard
, if I want to create a new line. But, that does not solve the problem if the text changes dynamically.
How can make multiple lines and let a label adapt to the content in macOS
?
You can check the following properties in the Xcode interface builder:
Programatically (the key is to use the underlying cell of the NSTextField):
let textfield: NSTextField = NSTextField(wrappingLabelWithString: "This is a very long text that requires a line break.")
textfield.frame = NSRect(x: 0.0, y: 0.0, width: 128.0, height: 96.0)
(textfield.cell as? NSTextFieldCell)?.isEditable = false
(textfield.cell as? NSTextFieldCell)?.wraps = true
(textfield.cell as? NSTextFieldCell)?.usesSingleLineMode = false
(textfield.cell as? NSTextFieldCell)?.lineBreakMode = NSLineBreakMode.byWordWrapping
self.view.addSubview(textfield)