1. 程式人生 > >iOS runtime防止button連續點選事件

iOS runtime防止button連續點選事件

在我們平時iOS開發過程中經常使用按鈕,按鈕的點選事件使用場景眾多。但是我們很少注意到當你快速連續點選同一個按鈕的時候,會產生多次響應。

一般的處理方法:

在點選按鈕事件裡面,把button.enabled = NO,執行結束再設定為YES。這樣也能實現,但是每次都得設定,比較繁瑣。

runtime方法:

runtime繫結button事件響應間隔。寫一個UIButton的Category---《UIButton+Click.h》,使用的時候匯入這個類別即可,一般在預編譯檔案.pch裡面全域性匯入。

下載路徑:

ios-button防止連續點選(runtime)UIButton-Click

外部呼叫程式碼

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    btn.backgroundColor = [UIColor redColor];
//    btn.timeInterval = 1;
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

-(void)btnClick{
    NSLog(@"點選按鈕了");
}

搞定!!!