views:

29

answers:

2

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...!

A: 

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?

Jason McCreary
Yep - they are VERY design heavy. They're overlay-buttons for a map and the indicate spots on this map (whithout having the geocode for that spot). So placing them in IB is very handy - building them programmatically would be a pain :)can you give me a hint how this «respondsTo»-thingy would be implemented? all I found so far was `respondsToSelector:@selector(`...Thanks for your help!
Urs
Fair enough. I imagine you would want to test something like `[aButton respondsToSelector:@selector(addTarget) ...]`
Jason McCreary
Well - thanks for the hint for using this. Although, it doesn't solve my problem. The error goes away, but the targetAction isn't applied to the button... Seems like I have to do this in IB :(
Urs
+1  A: 

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? ;)

Urs

related questions