button循环添加事件

button循环添加事件ide

对于要建立不少button时,而且外观类似,一个一个建立很麻烦,而且大码重复量很大,因此用循环比较方便,能够减小代码冗余。字体

我试过在页面跳转处,用Tag找到对应的button,可是会出现连续跳转的状况,这样是不可取的。因此,在用循环给button添加事件只能在for循环内部。orm

 

NSArray *title = @[@"注册", @"取消"];事件

 

    for (int i = 0; i < 2; i ++) {get

//建立buttonit

        _button = [UIButton buttonWithType:UIButtonTypeSystem];io

//肯定button的位置for循环

        _button.frame = CGRectMake(150 * i + 50, 330, 100, 50);select

//设置button的title循环

        [_button setTitle:title[i] forState:UIControlStateNormal];

//设置button的字体

        _button.titleLabel.font = [UIFont boldSystemFontOfSize:21];

//button添加到视图上

        [self.view addSubview:_button];

//给button添加事件

        switch (i) {

            case 0:

                [_button addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];

                break;

            case 1:

                [_button addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];

                break;

            default:

                break;

        }

        

    }

相关文章
相关标签/搜索