我在下面的代码上的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。

最佳答案

喜欢

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];

}

关于ios - 带IBAction的iOS UIButton,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33548622/

10-12 01:49