iOS小技巧--用runtime 解決UIButton 重複點擊問題

來源:互聯網
上載者:User

iOS小技巧--用runtime 解決UIButton 重複點擊問題
iOS小技巧–用runtime 解決UIButton 重複點擊問題什麼是這個問題

我們的按鈕是點擊一次響應一次, 即使頻繁的點擊也不會出問題, 可是某些情境下還偏偏就是會出問題.

通常是如何解決

我們通常會在按鈕點擊的時候設定這個按鈕不可點擊. 等待0.xS的延時後,在設定回來; 或者在操作結束的時候設定可以點擊.

- (IBAction)clickBtn1:(UIbutton *)sender{    sender.enabled = NO;    doSomething    sender.enabled = YES;}

如果涉及到按鈕不同狀態不同樣式的時候, 用enabled不見得夠用.還得額外加個變數來選項組.

- (IBAction)clickBtn1:(UIbutton *)sender{    if (doingSomeThing) return;    doingSomeThing = YES;    doSomething    doingSomeThing = NO;}

筆者舉的例子是直接在響應事件的周期內直接禁止點擊的. 如果想做1秒內禁止重複點擊的話,則得用performSelector:withObject:afterDelay:

漂亮的解決是怎樣的

有了重複的程式碼片段就是有了一個共性, 就可以抽象出來.

我們可以給按鈕添加一個屬性重複點擊間隔, 通過設定這個屬性來控制再次接受點擊事件的時間間隔.

@interface UIControl (XY)@property (nonatomic, assign) NSTimeInterval uxy_acceptEventInterval;   // 可以用這個給重複點擊加間隔@endstatic const char *UIControl_acceptEventInterval = UIControl_acceptEventInterval;- (NSTimeInterval)uxy_acceptEventInterval{    return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];}- (void)setUxy_acceptEventInterval:(NSTimeInterval)uxy_acceptEventInterval{    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(uxy_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);}

在app啟動的時候,我們hook 所有的按鈕的 event

@implementation UIControl (XY)+ (void)load{    Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));    Method b = class_getInstanceMethod(self, @selector(__uxy_sendAction:to:forEvent:));    method_exchangeImplementations(a, b);}@end

在我們的點擊事件裡呢,對點擊事件做下過濾

- (void)__uxy_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{    if (self.uxy_ignoreEvent) return;    if (self.uxy_acceptEventInterval > 0)    {        self.uxy_ignoreEvent = YES;        [self performSelector:@selector(setUxy_ignoreEvent:) withObject:@(NO) afterDelay:self.uxy_acceptEventInterval];    }    [self __uxy_sendAction:action to:target forEvent:event];}

實際使用起來就是這個樣子

    UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];    [tempBtn addTarget:self action:@selector(clickWithInterval:) forControlEvents:UIControlEventTouchUpInside];    tempBtn.uxy_acceptEventInterval = 0.5;

文章至此就結束了.雖然不推薦大範圍用runtime, 但是小範圍內使用還是可以解決不少小問題的.

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.