我动态制作了20个按钮,我得到了所有按钮的标签值。
但我需要知道如何使用该标签值。
我需要有关按标签值的每个按钮的信息 那么,我该如何使用这些标签值?
答案 0 :(得分:7)
您需要设置每个按钮的目标操作。
[button setTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];
然后像这样实施someMethod:
:
- (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
}
答案 1 :(得分:4)
为什么需要使用tag
来获取按钮。您可以直接从其操作方法中获取按钮引用。
- (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;
}
我希望您已为按钮添加了目标操作。
[button addTarget:self action:@selector(onButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
答案 2 :(得分:3)
您可以使用该标签来引用您的按钮。例如,您已将UIButton
添加到UIView *mainView
。要获得对这些按钮的引用,您应该写下以下内容:
UIButton *buttonWithTag1 = (UIButton *)[mainView viewWithTag:1];
答案 3 :(得分:3)
像这样设置标签:
for (createButtonIndex=0; createButtonIndex<buttonsCount; createButtonIndex++)
{
buttonCaps.tag=createButtonIndex;
}
并添加捕获标记的方法: -
-(void)buttonsAction:(id)sender
{
UIButton *instanceButton = (UIButton*)sender;
switch(instanceButton.tag)
{
case 1(yourTags):
//Code
break;
case 2:
//Code
break;
}
}
希望这有助于!!
答案 4 :(得分:1)
- (IBAction)buttonPressed:(id)sender {
UIButton selectedButton = (UIButton *)sender;
NSLog(@"Selected button tag is %d%", selectedButton.tag);
}
答案 5 :(得分: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;
答案 6 :(得分:0)
UIButton *btn = (UIButton *)[mainView viewWithTag:button.tag];