IOS UIButton与IBAction

时间:2015-11-05 15:31:17

标签: ios objective-c uibutton

我在下面的代码中为for循环创建了一些按钮。

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。

1 个答案:

答案 0 :(得分: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];

}