set title of buttons if clicked using only one method

Discussion in 'iOS Programming' started by spitzmuller, Dec 10, 2008.

  1. macrumors newbie

    Dec 10, 2008
    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
  2. macrumors member

    Aug 10, 2008
    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 ;
  3. thread starter macrumors newbie

    Dec 10, 2008
    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?
  4. macrumors regular

    Mar 24, 2008
    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.

Share This Page