我使用for循环创建了按钮。按钮完美无缺。现在我必须为所有动态按钮单独执行IB操作。我也设置了标签。我使用的代码如下。但是这个动作并没有确定我想要使用的确切按钮。
for (int i=0; i < 10; i++){
btnphoto=[[UIButton alloc]initWithFrame:CGRectMake(10,(30*i)+110,50,20)];
[btnphoto setTitle:@"Photo" forState:UIControlStateNormal];
[btnphoto addTarget:self action:@selector(someMethod:)forControlEvents:UIControlEventTouchUpInside];
btnphoto.tag=100 + i;
[self.view addSubview:btnphoto];
}
-(void)someMethod:(UIButton *)sender{
}
答案 0 :(得分:3)
试试这个 -
在someMethod方法中 -
UIButton *button = sender;
int buttonTagIndex = button.tag;
现在,buttonTagIndex为您提供所选按钮的标记索引。
答案 1 :(得分:3)
试试这个
for (int i=0; i < 10; i++){
UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(10,(30*i)+110,50,20)];
[button setTitle:@"Photo" forState:UIControlStateNormal];
[button addTarget:self action:@selector(someMethod:)forControlEvents:UIControlEventTouchUpInside];
button.tag=100 + i;
[self.view addSubview:button];
}
要显示不同的颜色,请先在阵列中添加颜色
NSMutableArray *colorArray=[[NSMutableArray alloc] initWithObjects:[UIColor redColor],[UIColor blueColor],[UIColor greenColor],nil];
然后
-(void)someMethod:(UIButton *)sender{
NSLog(@"Btn Tag = %d",sender.tag);
int randomNum=arc4random()%3;
[sender setBackgroundColor:[colorArray objectAtIndex:randomNum]];
}
答案 2 :(得分:2)
您必须从函数中实际访问按钮的tag属性,以确定哪个按钮调用了选择器。
-(void)someMethod:(UIButton *)sender {
UIButton *tappedButton = sender;
NSInteger tag = tappedButton.tag;
NSLog(@"This is the button with tag: %ld",tag);
[tappedButton setBackgroundColor:[UIColor redColor]];
}
答案 3 :(得分:2)
如果您想更改颜色或任何属性,则可以按照以下步骤进行操作
//我只是举例说明如何更改UIButton的标题,同样可以更改颜色属性...我刚刚在我的代码中使用了这个...
-(void)someMethod:(id)sender {
//1...this will change all the button title with string "Changed"
[sender setTitle:@"Changed" forState:UIControlStateNormal];
//2..now if you want to just change the property of uibutton on basis of tag value
[(UIButton *)[self.contentView viewWithTag:Your_TAG_VALUE] setTitle:@"JustChanged" forState:UIControlStateNormal];
}
答案 4 :(得分:0)
-(void)someMethod:(id)sender{
UIButton *btn = (UIButton *)sender;
int *btn_tag=btn.tag;
NSLog(@"This is the button with tag: %d", btn_tag);
}
答案 5 :(得分:0)
由于您已经为每个按钮设置了标签,因此只需执行以下操作即可确定触摸了哪个按钮
-(void)someMethod:(id)sender
{
UIButton *TouchedButton=(UIButton *)sender;
int TouchedButtonTag=[TouchedButton tag]; // Now you can uniquely identify your buttons by this tag.
// do your stuff for respective button touched event
switch([TouchedButton tag])
{
case :101
[TouchedButton setBackgroundColor:[UIColor redColor]];
break;
case :102
[TouchedButton setBackgroundColor:[UIColor redColor]];
break;
case :103
[TouchedButton setBackgroundColor:[UIColor blueColor]];
break;
// and so on...
}
}
答案 6 :(得分:0)
尝试上面的代码,这可能会有所帮助:
-(void)someMethod:(id)sender{
UIButton *btn = (UIButton *)[self.view viewWithTag:btn_tag];
switch([btn tag])
{
case :101
[btn setBackgroundColor:[UIColor redColor]];
break;
case :102
[btn setBackgroundColor:[UIColor redColor]];
break;
case :103
[btn setBackgroundColor:[UIColor blueColor]];
break;
}
}