2015-11-05 86 views
0

我在下面的代码上创建了for循环的一些按钮。带IBAction的IOS UIButton

UIView *buttonsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _viewEmoji.frame.size.width, 35)]; 
    [buttonsView setBackgroundColor:[UIColor greenColor]]; 
for (int i = 0; i < myObject.count; i ++) { 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [button setFrame:CGRectMake(35*i + 5, 0, 35, 35)]; 
     [button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", [myObject objectAtIndex:i]]] forState:UIControlStateNormal]; 
     [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside]; 
     [buttonsView addSubview:button]; 
    } 

现在,我如何点击按钮来处理事件。

每个按钮被点击,它将处理1个事件。例如:如果我有2个按钮是由for循环创建的。当我点击按钮1,它会记录1,当我点击按钮2,它会记录2.

+3

每个按钮提供一个独特的'tag'值。 – rmaddy

回答

1

不喜欢

UIView *buttonsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _viewEmoji.frame.size.width, 35)]; 
[buttonsView setBackgroundColor:[UIColor greenColor]]; 
for (int i = 0; i < myObject.count; i ++) { 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [button setFrame:CGRectMake(35*i + 5, 0, 35, 35)]; 
    [button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", [myObject objectAtIndex:i]]] forState:UIControlStateNormal]; 
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside]; 
    // set the tag for identify which button you pressed 
    button.tag = i; // else use --> [myObject objectAtIndex:i] 
    [buttonsView addSubview:button]; 
} 

    //here add your buttonsView to mainview 
self.view addsubview(buttonsView) 

// for button action 
-(void)clickButton:(UIButton*)sender 
{ 
    NSLog(@" Index: %d ", sender.tag); 
    [sender setBackgroundImage:[UIImage imageNamed:@"XXX.png"] forState:UIControlStateNormal]; 

} 
+3

我建议将每个按钮的标签设置为“i + 1”或其他避免给按钮标签为“0”的计算。 – rmaddy

+0

天啊!这是很样品。谢谢。 –

+0

简单的兄弟,**发件人**是你当前选择的按钮,你可以为你选择的按钮做任何事情,即所有 –