Programmatically generating UIButtons and associate those with IBAction

喜夏-厌秋 提交于 2019-12-20 10:33:13

问题


How do I do if I want to programatically generate a set of buttons and then associate those with IBActions? It's easy if I add the buttons in Interface Builder, but that I cannot do for this case.


回答1:


The buttons have the method - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents.

The code to use this would look like this:

UIButton *myButton = [[UIButton alloc] init...];
[myButton addTarget:something action:@selector(myAction) forControlEvents:UIControlEventTouchUpInside];

This assumes that your IBAction is named myAction and that something is the controller for which that action is defined.




回答2:


First, create the button:

UIButton * btn;

btn = [ [ UIButton alloc ] initWithFrame: CGRectMake( 0, 0, 200, 50 ) ];

Then adds an action:

[ btn addTarget: self action: @selector( myMethod ) forControlEvents: UIControlEventTouchDown ];

Then adds the button to a view:

[ someView addSubView: btn ];
[ btn release ];

UIControl reference UIButton reference



来源:https://stackoverflow.com/questions/2370031/programmatically-generating-uibuttons-and-associate-those-with-ibaction

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