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 {
}
第二種方法我個人更傾向一些;如果各位有好的方法,希望能夠交流;如果里面有一些不好的地方,希望指正!