Xcobe
Xcobe

Reputation: 111

iphone:access UIButton instance by Tag

I placed 6 UIButton on nib, I don't want to create 6 variables for each of button, is there any way to access buttons by their Tag or something else?

I found a method viewWithTag, but seems it is used for NSView.

THX~

Upvotes: 0

Views: 1845

Answers (4)

Oritm
Oritm

Reputation: 2121

Use:

- (IBAction)buttonTouched:(id)sender{

    NSInteger tag = [sender tag];

    if (tag == 1) {
        NSLog(@"You Pressed 1");
    } else if (tag == 2) {
        NSLog(@"You Pressed 2");
    }

}

Now in the the Interface Builder, set the tag to 1 or 2.

Upvotes: 0

visakh7
visakh7

Reputation: 26390

- (IBAction)buttonPressed:(id)sender{
        UIButton *button = (UIButton *)sender;
        NSLog(@"%d",button.tag);

}

Upvotes: 0

Ruben Marin
Ruben Marin

Reputation: 1637

If you created them by Interface Builder, you must go to IB and assign a unique tag to each button (1, 2, ...) and inside your code you can refer to them by UIButton *button1 = (UIButton *)[self.view viewWithTag:1], UIButton *button2 = (UIButton *)[self.view viewWithTag:2] and so on.

Upvotes: 1

tamasgal
tamasgal

Reputation: 26259

You usually don't need to create "variables" for control elements, except you want to manipulate them during runtime. You can just create your methods and link them to specific actions (push up inside) of the UIButtons. The methods will be called without the need of instance variables of the UIButtons.

Otherwise, if you want to set the buttons enabled/disabled or manipulate any other attributes, you have to create variables for them. I don't see why you should do this with tags, because creating pointers to the UIButton instances requires only 2 lines of code (and one to synthesize them all).

Upvotes: 0

Related Questions