IOS 防止UIButton 重復(fù)點(diǎn)擊

我分別用OC / Swift 寫兩個(gè)常用的防止UIButton重復(fù)點(diǎn)擊的方法 其實(shí)有三種方法 不過那一種太low 不想寫

OC 1. 第一種 cancelPreviousPerformRequestsWithTarget

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    btn.backgroundColor = [UIColor redColor];
    [btn addTarget:self action:@selector(TB_btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
-(void)TB_btnClick
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(PrintHelloWorld) object:nil];
    [self performSelector:@selector(PrintHelloWorld) withObject:nil afterDelay:.4];
}
-(void)PrintHelloWorld
{
   NSLog(@"點(diǎn)擊了有延遲嗎");
}

//  間距都會(huì)超過0.4s
2017-06-02 18:51:24.351 button_repeat[12220:301281] 點(diǎn)擊了有延遲嗎
2017-06-02 18:51:24.895 button_repeat[12220:301281] 點(diǎn)擊了有延遲嗎
2017-06-02 18:51:25.798 button_repeat[12220:301281] 點(diǎn)擊了有延遲嗎
2017-06-02 18:51:28.222 button_repeat[12220:301281] 點(diǎn)擊了有延遲嗎

OC 2. 第二種 通過Runtime 寫一個(gè)UIButton 類別

// 這是類別的源碼

#import "UIButton+TBCustom.h"
#import <objc/runtime.h>

@interface UIButton()

@property (nonatomic, assign) NSTimeInterval custom_acceptEventInterval; // 可以用這個(gè)給重復(fù)點(diǎn)擊加間隔

@end

@implementation UIButton (TBCustom)

+ (void)load{
    Method systemMethod = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    SEL sysSEL = @selector(sendAction:to:forEvent:);
    
    Method customMethod = class_getInstanceMethod(self, @selector(custom_sendAction:to:forEvent:));
    SEL customSEL = @selector(custom_sendAction:to:forEvent:);
    
    //添加方法 語法:BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types) 若添加成功則返回No
    // cls:被添加方法的類  name:被添加方法方法名  imp:被添加方法的實(shí)現(xiàn)函數(shù)  types:被添加方法的實(shí)現(xiàn)函數(shù)的返回值類型和參數(shù)類型的字符串
    BOOL didAddMethod = class_addMethod(self, sysSEL, method_getImplementation(customMethod), method_getTypeEncoding(customMethod));
    
    //如果系統(tǒng)中該方法已經(jīng)存在了,則替換系統(tǒng)的方法  語法:IMP class_replaceMethod(Class cls, SEL name, IMP imp,const char *types)
    if (didAddMethod) {
        class_replaceMethod(self, customSEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
    }else{
        method_exchangeImplementations(systemMethod, customMethod);
        
    }
}

- (NSTimeInterval )custom_acceptEventInterval{
    return [objc_getAssociatedObject(self, "UIControl_acceptEventInterval") doubleValue];
}

- (void)setCustom_acceptEventInterval:(NSTimeInterval)custom_acceptEventInterval{
    objc_setAssociatedObject(self, "UIControl_acceptEventInterval", @(custom_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval )custom_acceptEventTime{
    return [objc_getAssociatedObject(self, "UIControl_acceptEventTime") doubleValue];
}

- (void)setCustom_acceptEventTime:(NSTimeInterval)custom_acceptEventTime{
    objc_setAssociatedObject(self, "UIControl_acceptEventTime", @(custom_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)custom_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    
    // 如果想要設(shè)置統(tǒng)一的間隔時(shí)間,可以在此處加上以下幾句
    // 值得提醒一下:如果這里設(shè)置了統(tǒng)一的時(shí)間間隔,只會(huì)影響UIButton, 如果想統(tǒng)一設(shè)置,也想影響UISwitch,建議將UIButton分類,改成UIControl分類,實(shí)現(xiàn)方法是一樣的
     if (self.custom_acceptEventInterval <= 0) {
         // 如果沒有自定義時(shí)間間隔,則默認(rèn)為.4秒
        self.custom_acceptEventInterval = .4;
     }
    
    // 是否小于設(shè)定的時(shí)間間隔
    BOOL needSendAction = (NSDate.date.timeIntervalSince1970 - self.custom_acceptEventTime >= self.custom_acceptEventInterval);
    
    // 更新上一次點(diǎn)擊時(shí)間戳
    if (self.custom_acceptEventInterval > 0) {
        self.custom_acceptEventTime = NSDate.date.timeIntervalSince1970;
    }
    
    // 兩次點(diǎn)擊的時(shí)間間隔小于設(shè)定的時(shí)間間隔時(shí),才執(zhí)行響應(yīng)事件
    if (needSendAction) {
        [self custom_sendAction:action to:target forEvent:event];
    }
}

這是測試代碼

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    btn.backgroundColor = [UIColor redColor];
    [btn addTarget:self action:@selector(TB_btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

-(void)TB_btnClick
{
    NSLog(@"點(diǎn)擊了有延遲嗎");
}

// 測試數(shù)據(jù) 都不會(huì)少于0.4s
2017-06-02 18:56:48.334 button_repeat[12380:305861] 點(diǎn)擊了有延遲嗎
2017-06-02 18:56:50.110 button_repeat[12380:305861] 點(diǎn)擊了有延遲嗎
2017-06-02 18:56:50.702 button_repeat[12380:305861] 點(diǎn)擊了有延遲嗎
2017-06-02 18:56:51.270 button_repeat[12380:305861] 點(diǎn)擊了有延遲嗎

Swift

swift 第一種

import UIKit

class SWIFTViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

       view.backgroundColor = UIColor.gray
       // 第一種方式
        StepOne()
    }

    fileprivate func StepOne(){
      let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
      btn.backgroundColor = UIColor.green
      btn.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
      view.addSubview(btn)
    }
    func btnClick(_ btn:UIButton){
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(printHelloWorld), object: "abc")
        self.perform(#selector(printHelloWorld), with: nil, afterDelay: 0.4)
    }
    func printHelloWorld(){
        print("Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲")
    }
}

// 注釋
Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲
Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲
Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲

Swift 第二種. 參考網(wǎng)上的大牛們的

// 首先給UIButton 協(xié)議個(gè)類的擴(kuò)展
import UIKit
import Foundation

public extension UIButton{

    private struct cs_associatedKeys {
        static var accpetEventInterval = "cs_acceptEventInterval"
        static var acceptEventTime = "cs_acceptEventTime"
    }
    /**
     重復(fù)點(diǎn)擊的時(shí)間間隔--自己手動(dòng)隨意設(shè)置
     利用運(yùn)行時(shí)機(jī)制 將accpetEventInterval值修改
     */
    var cs_accpetEventInterval: TimeInterval {
        get {
            if let accpetEventInterval = objc_getAssociatedObject(self, &cs_associatedKeys.accpetEventInterval) as? TimeInterval {

                return accpetEventInterval            }
            return 0.4
        }
        set {
            objc_setAssociatedObject(self, &cs_associatedKeys.accpetEventInterval, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    /**
     重復(fù)點(diǎn)擊的時(shí)間間隔--自己手動(dòng)隨意設(shè)置
     利用運(yùn)行時(shí)機(jī)制 將acceptEventTime值修改
     */
    var cs_acceptEventTime : TimeInterval {
        get {
            if let acceptEventTime = objc_getAssociatedObject(self, &cs_associatedKeys.acceptEventTime) as? TimeInterval {
                return acceptEventTime
            }
            return 0.4
        }
        set {
            objc_setAssociatedObject(self, &cs_associatedKeys.acceptEventTime, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    /**
     重寫初始化方法,在這個(gè)方法中實(shí)現(xiàn)在運(yùn)行時(shí)方法替換
     */
    override open class func initialize() {
        let changeBefore: Method = class_getInstanceMethod(self, #selector(UIButton.sendAction(_:to:for:)))
        let changeAfter: Method = class_getInstanceMethod(self, #selector(UIButton.cs_sendAction(action:to:for:)))
        method_exchangeImplementations(changeBefore, changeAfter)
    }
    /**
     在這個(gè)方法中判斷接收到當(dāng)前事件的時(shí)間間隔是否滿足我們所設(shè)定的間隔,會(huì)一直循環(huán)調(diào)用到滿足才會(huì)return
     */
    func cs_sendAction(action: Selector, to target: AnyObject?, for event: UIEvent?) {
        if NSDate().timeIntervalSince1970 - self.cs_acceptEventTime < self.cs_accpetEventInterval {
            return
        }
        if self.cs_accpetEventInterval > 0 {
            self.cs_acceptEventTime = NSDate().timeIntervalSince1970
        }
        self.cs_sendAction(action: action, to: target, for: event)
    }
}

第二種 測試

import UIKit

class SWIFTViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

       view.backgroundColor = UIColor.gray

       // 第二種方式
        StepTwo()
    }

    fileprivate func StepTwo(){
        let btn = UIButton(frame: CGRect(x: 100, y: 250, width: 100, height: 100))
        btn.backgroundColor = UIColor.red
        btn.addTarget(self, action: #selector(btnClickTwo(_:)), for: .touchUpInside)
        view.addSubview(btn)
    }
    func btnClickTwo(_ btn:UIButton){
       print("Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲")
    }
}

// 測試
Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲
Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲
Swift 打印不出時(shí)間- 如果你知道 請(qǐng)大神 告知 --- 是否有延遲

github 地址 https://github.com/tianbinbin/Call_UIButton_Repeat 喜歡點(diǎn)個(gè)贊??

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容