Search code examples
macoscocoaconstraintsnsviewnstextfield

cocoa osx add nstextfields programmatically


I'm making a project for osx and I need to add multiple NSTextfields to a custom view (NSView) programmatically. I don't know how to achieve this correctly.

This is what I need to do:

enter image description here

I know how to create the NSTextfiedls and how to add them to the NSView, but i dont know how to config them to show like in the image and set them any constraints in code. I'm using autolayout.


Solution

  • Have a look at using the NSStackView class to hold your text fields. For simple set-ups - like the one in your screenshot - this class does the auto-layout work for you.

    enter image description here

    To help you get to grips with it, Apple provide a sample demo called InforBarStackView .


    The screenshot below is from a program which added a stack view instance to an otherwise empty window in Interface Builder.

    enter image description here

    The text fields were added with the following code:

    // AppDelegate has a stackView outlet
    for each in 0...2 {
        var f = NSTextField()
        f.translatesAutoresizingMaskIntoConstraints = false
        stackView.addView(f, inGravity:.Top)
    }