maseth
maseth

Reputation: 841

How to dynamically add component in Cocoa

Is it possible in Cocoa to add component on view programatically? The UI is created using the Interface Builder from Xcode. I just want to add some NSButtons but its quantity and positions will be known at the runtime and user input.

Does anyone knows is it possible and how it could be done and how positioning these ynamic components?

Upvotes: 1

Views: 711

Answers (1)

T. Benjamin Larsen
T. Benjamin Larsen

Reputation: 6383

Of course it is possible. Adding a subview:

UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; // or UIButton, UIScrollView, or any other view-based class you make think of
[self addSubview:subview];

etc.

Or to be more precise for a button it would be something like this:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
aButton.frame = CGRectMake(0, 0, 100, 100);
[aButton addTarget:self action:@selector(methodName) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:aButton]; // if done from the view self.view if done from the controller

Ah, sorry just noticed it was OSX, not iOS, but the basics are the same. Have a look at the NSButton class instead.

NSButton *aButton = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; // x, y, width, height

should get you started.

Upvotes: 1

Related Questions