Objective-C add an NSButton to my iphone app at runtime
I am absolutely cl开发者_运维技巧ueless on this front! Step-by-step explanation earns bonus points.
In iOS We have UIButtons (not NSButtons)
Here is how to create an UIButton programmatically:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //3
[button setFrame:CGRectMake(320, 0, 100,100 )];
[button setTitle:@"PressMe!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];//2
[aView addSubview:button]; //1
and :
- (void)buttonPressed:(UIButton *)sender{
//do something here ;)
[sender setTitle:@"PressMe!. Again" forState:UIControlStateNormal];
}
1: if you are in a UIViewController
, then aView
will be self.view
if you are somewhere else, just pass the view that will contain your button
2: the easiest case is like that but you can set any object as a target. That object must have to have the method you pass in the @selector(...)
. Otherwise you app will crash when pressing the button.
Not exactly sure of all the steps to do that in code, but what I would do is use the interface builder to create the button where you want it. Then when you load the view, make the button hidden in the viewDidLoad or viewDidAppear method. Make the button visible when you need to. Hope this helps.
精彩评论