Georges Oates Larsen
Georges Oates Larsen

Reputation: 7102

Objective-C add an NSButton to my iphone app at runtime

I am absolutely clueless on this front! Step-by-step explanation earns bonus points.

Upvotes: 2

Views: 4905

Answers (2)

nacho4d
nacho4d

Reputation: 45108

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.

Upvotes: 4

HM1
HM1

Reputation: 1684

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.

Upvotes: 2

Related Questions