user3572147
user3572147

Reputation: 21

How do I get the name from a UIButton?

I am new to xcode, and I am trying to make a generic button press method. I want it to check the name (not the title) of the button and then I want to do some string manipulation to set some values.

I have a button setup in my ViewController.h

@property (strong, nonatomic) IBOutlet UIButton *button_1_3;

Then I have a generic method in my ViewController.m

- (IBAction)buttonPress:(id)sender
{
    UIButton *bSender = (UIButton *)sender;

    self.char1Text1.text = bSender.titleLabel.text; // this is the bit that I am not getting
}

So a bunch of my buttons are going to have the same text on them, what I want to see is the "button_1_3". I was hoping there was a "bSender.name" option, but I am yet to find it.

any help would be appreciated

Upvotes: 0

Views: 3514

Answers (4)

Roland Keesom
Roland Keesom

Reputation: 8298

Give all your buttons a tag (this can also be done in Interface Builder)

button_1_0.tag = 0;
button_1_1.tag = 1;
button_1_2.tag = 2;
button_1_3.tag = 3;

In your buttonPress: method check the tag and show a different text

- (IBAction)buttonPress:(id)sender
{
    UIButton *bSender = (UIButton *)sender;
    switch (bSender.tag) {
        case 0:
            self.char1Text1.text = @"first text";
            break;
        case 1:
            self.char1Text1.text = @"second text";
            break;
        case 2:
            self.char1Text1.text = @"thrid text";
            break;
        case 3:
            self.char1Text1.text = @"fourth text";
            break;
        default:
            break;
    }
}

Upvotes: 4

Silviu St
Silviu St

Reputation: 1842

- (IBAction)buttonPress:(id)sender
{
    UIButton *bSender = (UIButton *)sender;
    //uh, and don't forget to set button's outlet or it won't work
    if(bSender==self.button_1_3){
         //button pressed is button_1_3..do manipulation for that button.
    }


}

Upvotes: 0

Aleksander Prenga
Aleksander Prenga

Reputation: 400

Just call the method below and it will give you what you need:

- (IBAction)buttonPress:(id)sender
{
    NSString* str1 = [sender titleForState:UIControlStateNormal];
    NSLog(@"%@", str1);
}

Upvotes: 0

Léo Natan
Léo Natan

Reputation: 57060

Variable names are there for your easy development, but are not retained when you compile your app.

You need to create a mapping between the buttons and their names. One easy way to achieve this is to assign each button a tag, and then create a mapping between tags and names. You can then get the name by _tagNameMapping[@(sender.tag)];.

Moreover, since tags are numeric, you can switch(sender.tag) and decide your logic, if you chose to.

Upvotes: 2

Related Questions