PDA

View Full Version : set title of buttons if clicked using only one method




spitzmuller
Dec 10, 2008, 04:01 PM
Hi there

Newbie question - beware :)

I have 9 buttons on my view and I'd like to change the title of them when they get clicked. I dont want to declare nine different methods but just one that handles all. I thought I could use something like this

- (IBAction)setTitle:(id)sender{
sender.title = @"sometitle";
}

It's probably totally stupid but I am new to iPhone programming and have no clue how to make this work. Any help appreciated



beachdog
Dec 10, 2008, 04:37 PM
Yes, you could do this. You should assign a unique tag value to each of your buttons so you can determine who is sending you the event, assuming you want to write a title differently depending...


-(void) onClicked:(id) sender {
UIButton* btn = (UIButton*) sender;
switch( btn.tag ) {
case 0: [btn setTitle:@"title 1" forState:UIControlStateNormal]; break ;
case 1 :[btn setTitle:@"title 2" forState:UIControlStateNormal]; break ;
//etc...

spitzmuller
Dec 11, 2008, 02:44 AM
Hi there Beach dog

You actually just answered a few other questions I would have had as well. Thanks a lot!

Just one thing: is it possible to have a button send custom arguments in a call like this?

SqueegyX
Dec 11, 2008, 12:13 PM
Hi there Beach dog

You actually just answered a few other questions I would have had as well. Thanks a lot!

Just one thing: is it possible to have a button send custom arguments in a call like this?

No, but you can track some instance variables that correspond to buttons.

//uses an instance variable decalred in your .h file
myArray = [[NSArray alloc] initWithObjects:@"one", @"two", @"three", nil]

// Then later in your button method
UIButton *button = (UIButton *)sender;
NSLog(@"Pressed button %@", [myArray objectAtIndex:button.tag]);


So you store your own arguments, and then fetch them based on what button was pressed.