2011-09-02 1 views
3

私は20個のボタンを動的に作りました。すべてのボタンのタグ値を取得しました。iPhoneでボタンのタグ値を取得する

しかし、私はそのタグ値の使い方を知る必要があります。

タグ値で押されたすべてのボタンに関する情報が必要です。
これらのタグ値はどのように使用しますか?

答えて

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

このタグを使用してボタンを参照できます。たとえば、UIView *mainViewUIButtonを追加したとします。あなたは次のように記述する必要があり、そのボタンへの参照を取得するには:

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

いずれのビューでもボタンを追加していない場合、タグ値を使用してそのボタンを取得できますか? – NiKKi

+0

@NiKKi "" ... "を取得しなかった場合" ...何を検索したいですか? – Nekto

7

をあなたは各ボタンのターゲットアクションを設定する必要があります。あなたがボタンを取得するためにtagを使用する必要がないのはなぜ

- (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 
} 
4

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

次に、このようなsomeMethod:を実装しています。アクションメソッドからボタンリファレンスを直接取得することができます。

- (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; 
} 

ボタンのターゲットアクションを追加していただければ幸いです。タグを

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

をし、トラップにメソッドを追加::

[button addTarget:self action:@selector(onButtonPressed:) 
      forControlEvents:UIControlEventTouchUpInside]; 
1
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; 
3

は次のようにタグを設定する -

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

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

ホープ、このことができます!

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