user1053078 user1053078 - 1 year ago 90
iOS Question

How do I use a switch statement to find if a UIButton is pressed?

I’m making an ios application and am having trouble using a switch statement to see if a UIButton element was pressed.
This is who I want the end product to work: I have multiple uncolored images (by uncolored I mean white, a UIImage). When an uncolored image is tapped a subview opens with colored boxes (UIButtons, 24 of them, each with individual colors.). When a colored box button is selected and the back button on the toolbar is pressed, the subview closes and the original view re-appears with the uncolored image (the one selected to open the subview) now colored with the desired color selected in the subview.

I want to use a switch statement to find which uncolored image and which color was selected (all UIButton elements). I do not know what to put as an expression in the switch statement because I’m dealing with UIButtons. The rest of the switch statement compares the value of the UIButton element to see if it’s equal to YES (when the button is pressed), and if it is, it returns a string. I also want to know how to connect an IBAction to a UIImage (so when the images are tapped a subview opens).

Answer Source

I'm a little rusty on iOS development but you could probably do the following:

Set the buttons to the same event handler and use the sender attribute to get to the tag element of the button which you can specify to each button.

- (IBAction) doStuff:(id) sender {
UIButton *button = (UIButton*) sender;
   //do stuff

If this doesn't work out for you, you can use any of the button properties you see fit to differentiate between them such as title, title color and so on.

For best practices i'd advise you to also check if the sender is of type UIButton before trying to cast it into an object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download