Critter
Critter

Reputation: 462

Multiple UIButtons 1 function

Basically I need to have several buttons in a view. I would like them to all call one function so that I can keep track of a 'state'.

How can I tell which button called the function? Is there anyway to get the text of the sender?

Upvotes: 3

Views: 1118

Answers (3)

Jonah
Jonah

Reputation: 17958

In iOS action methods, including IBAction methods, can have any of the following signatures (see "Target-Action in UIKit"):

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event

If you use a method signature which accepts the sender then you have access to the object which triggered the action. You can then access properties on the calling object including its title and tag. You can also compare the sender to pointers you may already have to your buttons to determine which button is the sender of this particular event.

I favor comparing pointers because I believe that if (sender == self.nextPageButton) is easier to understand and less likely to break than if (sender.tag == 4) or if ([((UIButton *)sender).currentTitle isEqualToString:@"foo"]). Looking at tags in IB tells you nothing about what the code assumes they mean and if they are or are not important. Titles will change as you update your UI or localize your app and those changes should not require code changes as well.

Upvotes: 5

devsri
devsri

Reputation: 6183

You need not set the tag explicitly. You can define the IBOutlets of the UIButton in your .h file and their property as well as

@property (nonatomic , retain) IBOutlet UIButton *myButton;

and the method as

-(IBAction) browse : (id) sender; 

in the .m file you can implement the method as

-(IBAction) browse : (id) sender{

    if((UIButton *)sender == myButton){/*add the action here*/}
 } 

Add more if statements in the method for as many buttons you wish. Do connect the IBOutlets of all the respective buttons and also the selector browse.

Do remeber to release the IBOutlets in the dealloc method to prevent any memory leakage.

Hope this helps!!

Upvotes: 1

MarkPowell
MarkPowell

Reputation: 16540

Set the tag attribute of the Button.

You can do this in Interface Builder (just look through the fields).

Then in code:

if (sender.tag == 0) {
} else if (sender.tag == 1)

etc.

Upvotes: 3

Related Questions