首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带IBAction的IOS IBAction

带IBAction的IOS IBAction
EN

Stack Overflow用户
提问于 2015-11-05 15:31:17
回答 1查看 185关注 0票数 0

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

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-05 15:43:18

喜欢

代码语言:javascript
复制
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];

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33548622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档