简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM