setting target for a UIButton which was made in IB
I have a UIView with a bunch of buttons in it (something like 200 of them)...
The view was set up in IB so I would have to manually wire every button with a single handler...
I'm trying to traverse the subviews of the view, looking for buttons and then set the button's target programmatically... which results in a crash (I get the compile warning «UIButton may not respond to addTarget...»).
this is the loop:
for(UIButton *aButton in self.view.subviews){
if([aButton isKindOfClass:[UIButton class]]){
[aButton addTarget:self selector:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
}
}
I can access some of the properties of the button, like visibility开发者_开发百科 and title... but not the action?
Any help greatly appreciated...!
wow - it was actually pretty simple - the guys over at devforums.apple.com gave me the hint...
for(UIButton *aButton in self.view.subviews){
if([aButton isKindOfClass:[UIButton class]]){
[aButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
}
}
Can you spot the difference? ;)
You could use respondsTo
or some other variant to avoid getting the error. This would ensure you can set the action for aButton
.
However, if you are looping over all these buttons anyway, why not just build them programmatically? Are they design heavy?
you should mark your answer as correct.
But just in case anybody else comes:
It should be:
addTarget:self action:@selector(buttonClick:)
instead of:
addTarget:self selector:@selector(buttonClick:)
精彩评论