0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3065901
  • 4,678
  • 11
  • 30
  • 52

2 Answers2

1

You can specify the frames for each Text field. like

NSRect rect = NSMakeRect(xPos,SuperView.frame.size.height - (padding + control_Height),control_Width,control_Height);
`for(int i = 0;i < 3;i++)
{

NSTextField *textField = [[NSTextField alloc] initWithFrame:rect];
[superView addSubView:textField];
[textField release];
rect.origin.y -= (padding + control_Height);

}`
Sheen Vempeny
  • 818
  • 1
  • 5
  • 8
1

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)
}
Paul Patterson
  • 6,840
  • 3
  • 42
  • 56
  • I dont know how to use stackview. Could you post a more complex example? With stackview can i add multiple items without limit? – user3065901 Feb 05 '15 at 09:54
  • *Could you post a more complex example?* - have updated post to provide a link to an Apple demo showcasing the ``NSStackView``. *Can I add multiple items with limit?* - questions like this are best answered by the documentation for the class. From what I can see the ``NSStackView`` class reference mentions to limit on the subviews it can handle. – Paul Patterson Feb 05 '15 at 12:08