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

£可爱£侵袭症+ 提交于 2019-12-06 10:38:10

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!