iOS开发:给多个UIButton添加不同的点击事件

UIButton在开发中的使用量是不用多说的,但是给button添加方法,再次还是有必要说一下的addTarget...,好吧,别打,我不说了!

通过for循环添加多个button,给button添加不同的点击事件

方法一:通过给button赋不同的tag值

凡是遇到这种需求时,我都是通过给button赋不同的tag值,先添加同一个点击事件,然后根据不同的tag值来做不同的处理,代码如下:

- (void)addButton
{
    for (int i = 0; i < 10; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 100 + i;
        [button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
}

![Uploading 顶部图片拉伸_502545.gif . . .]

- (void)click
{
    //此处根据不同的tag值,作出不同的点击事件
}
方法二:把方法名放到数组里面

但是时间久了,就不想通过if这些判断添加不同的方法了;找到了NSSelectorFromString这个方法,我们需要把方法名添加到数组里面,然后再创建button时赋不同的方法;代码如下:

- (void)addButton
{
    NSArray *array = @[@"test1", @"test2", @"test3"];
    for (int i = 0; i < array.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:NSSelectorFromString(array[i]) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
}

- (void)test1 {

}

- (void)test2 {

}

- (void)test3 {

}

第二种方法我个人更倾向一些;如果各位有好的方法,希望能够交流;如果里面有一些不好的地方,希望指正!

你可能感兴趣的:(iOS开发:给多个UIButton添加不同的点击事件)