button循环添加事件

button循环添加事件

对于要创建很多button时,并且外观相似,一个一个创建很麻烦,并且大码重复量很大,所以用循环比较方便,可以减少代码冗余。

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

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

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

//创建button

        _button = [UIButton buttonWithType:UIButtonTypeSystem];

//确定button的位置

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

//设置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;

        }

        

    }

    

原文地址:https://www.cnblogs.com/d-mm/p/5210234.html