开发者

Getting Button Tag Value in iPhone

I have made 20 Buttons dynamically, and I got the tag values of all Buttons.

But I need to know开发者_开发技巧 how to use that tag values.

I need information on every button pressed with tag values.

So, how do I use those tag values?


You need to set target-action of each button.

[button setTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];

Then implement someMethod: like this:

- (void)someMethod:(UIButton *)sender {
    if (sender.tag == 1) {
        // do action for button with tag 1
    } else if (sender.tag == 2) {
        // do action for button with tag 2
    } // ... and so on
}


Why do you need to use the tag to get the button. You can directly get the buttons reference from its action method.

- (void)onButtonPressed:(UIButton *)button {

    // "button" is the button which is pressed
    NSLog(@"Pressed Button: %@", button);

    // You can still get the tag
    int tag = button.tag;
}

I hope you have added the target-action for the button.

[button addTarget:self action:@selector(onButtonPressed:) 
             forControlEvents:UIControlEventTouchUpInside];


You can get reference to that your buttons using that tags. For example, you've added UIButtons to UIView *mainView. To get reference to that buttons you should write following:

UIButton *buttonWithTag1 = (UIButton *)[mainView viewWithTag:1];


Set the tags like this :

for (createButtonIndex=0; createButtonIndex<buttonsCount; createButtonIndex++) 
    {
buttonCaps.tag=createButtonIndex;
}

And add the method to trap the tags :-

-(void)buttonsAction:(id)sender
{
    UIButton *instanceButton = (UIButton*)sender;

switch(instanceButton.tag)
{
case 1(yourTags):
//Code
break;
case 2:
//Code
break;
}
}

Hope this Helps !!


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


    usefully we use btn tag if You Write One Function For (more than one) Buttons .in action if we want to write separate Action For button at that situvation we use btn tag.it can get two ways  

    I) case  sender.tag
    //if we have four buttons Add,mul,sub,div having Same selector and add.tag=10
    mul.tag=20,sub.tag=30,div.tag=40;
    -(IBAction) dosomthing:(id)sender   
    {
    int x=10;
    int y=20;
    int result;
     if(sender.tag==10)
    {
    result=x+y;

    }else if(sender.tag==20)
    {
    result=x*y;

    }else if(sender.tag==30)
    {
    result=x-y;

    }else if(sender.tag==40)
    {
    result=x/y;

    }
    NSLog(@"%i",result);

    }

2)Case
UIButton *btn=[self.view viewWithTag:10];
then you got object of add button uyou can Hide It With btn.hidden=YES;


UIButton *btn = (UIButton *)[mainView viewWithTag:button.tag];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜