Search code examples
swiftmacosnstextfieldnsscrollviewnsstackview

macOS NSTextField,NSStackView,NSScrollView How to achieve wrapped text in a scrollable list?


New to macOS development and trying to create some very basic layouts, however I'm struggling to add NSTextFields to a NSStackView situated within an NSScrollView, thus far I have wrote the following however it seems to restrict the text to a single line, resizing the window to fit....Image

@IBOutlet weak var sv: NSStackView!

let lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    sv.autoresizesSubviews = true
    for i in 0..<10{
        var test = NSTextField(string: lorem)
        test.isEditable = false
        test.isBordered = false
        test.translatesAutoresizingMaskIntoConstraints = false
        test.usesSingleLineMode = false
        test.lineBreakMode = .byCharWrapping
        test.wantsLayer = true
        test.layer?.cornerRadius = 5

        sv.addView(test, in: .top)

    }}

Solution

  • Using NSTextField(string:) as the initializer freezes the field as a single line. Try this convenience initializer instead:

    let test = NSTextField(wrappingLabelWithString: lorem)
    

    …and don't bother with .isEditable, .translatesAutoresizingMaskIntoConstraints, or .usesSingleLineMode.