zoukankan      html  css  js  c++  java
  • iOS---防止UIButton重复点击的三种实现方式

    通常, 我们会采用如下的一些措施来防止重复点击UIButton:

    使用UIButton的enabled或userInteractionEnabled

    使用UIButton的enabled属性, 在点击后, 禁止UIButton的交互, 直到完成指定任务之后再将其enable即可.

    [btn addTarget:self action:@selector(actionFixMultiClick_enabled:) forControlEvents:UIControlEventTouchUpInside];
    
    // xxx
    
    - (void)actionFixMultiClick_enabled:(UIButton *)sender {
        sender.enabled = NO;
        [self btnClickedOperations];
    }
    
    - (void)btnClickedOperations {
        self.view.backgroundColor = [UIColor colorWithRed:((arc4random() % 255) / 255.0)
                                                    green:((arc4random() % 255) / 255.0)
                                                     blue:((arc4random() % 255) / 255.0)
                                                    alpha:1.0f];
    
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"btnClickedOperations");
            btn.enabled = YES;
        });
    }
    

    使用performSelector:withObject:afterDelay:和cancelPreviousPerformRequestsWithTarget

    使用这种方式, 会在连续重复点击UIButton的时候, 自动取消掉之前的操作, 延时1s后执行实际的操作.
    这样, 看起来会比第一种和第三种稍微延迟执行实际的操作.

    [btn addTarget:self action:@selector(actionFixMultiClick_performSelector:) for
    
    // xxx
    
    - (void)actionFixMultiClick_performSelector:(UIButton *)sender {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(btnClickedOperations) object:nil];
    
        [self performSelector:@selector(btnClickedOperations) withObject:nil afterDelay:1];
    }
    

    使用runtime来对sendAction:to:forEvent:方法进行hook

    UIControl的sendAction:to:forEvent:方法用于处理事件响应.
    如果我们在该方法的实现中, 添加针对点击事件的时间间隔相关的处理代码, 则能够做到在指定时间间隔中防止重复点击.

    首先, 为UIButton添加一个Category:

    @interface UIButton (CS_FixMultiClick)
    
    @property (nonatomic, assign) NSTimeInterval cs_acceptEventInterval; // 重复点击的间隔
    
    @property (nonatomic, assign) NSTimeInterval cs_acceptEventTime;
    
    @end
    

    Category不能给类添加属性, 所以以上的cs_acceptEventInterval和cs_acceptEventTime只会有对应的getter和setter方法, 不会添加真正的成员变量.
    如果我们不在实现文件中添加其getter和setter方法, 则采用*** btn.cs_acceptEventInterval = 1; *** 这种方法尝试访问该属性会出错.

    2016-06-29 14:04:52.538 DemoRuntime[17380:1387981] -[UIButton setCs_acceptEventInterval:]: unrecognized selector sent to instance 0x7fe8e154e470
    

    在实现文件中通过runtime的关联对象的方式, 为UIButton添加以上两个属性. 代码如下:

    #import "UIControl+CS_FixMultiClick.h"
    #import <objc/runtime.h>
    
    @implementation UIButton (CS_FixMultiClick)
    
    // 因category不能添加属性,只能通过关联对象的方式。
    static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";
    
    - (NSTimeInterval)cs_acceptEventInterval {
        return  [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
    }
    
    - (void)setCs_acceptEventInterval:(NSTimeInterval)cs_acceptEventInterval {
        objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(cs_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    static const char *UIControl_acceptEventTime = "UIControl_acceptEventTime";
    
    - (NSTimeInterval)cs_acceptEventTime {
        return  [objc_getAssociatedObject(self, UIControl_acceptEventTime) doubleValue];
    }
    
    - (void)setCs_acceptEventTime:(NSTimeInterval)cs_acceptEventTime {
        objc_setAssociatedObject(self, UIControl_acceptEventTime, @(cs_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    
    // 在load时执行hook
    + (void)load {
        Method before   = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
        Method after    = class_getInstanceMethod(self, @selector(cs_sendAction:to:forEvent:));
        method_exchangeImplementations(before, after);
    }
    
    - (void)cs_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
        if ([NSDate date].timeIntervalSince1970 - self.cs_acceptEventTime < self.cs_acceptEventInterval) {
            return;
        }
    
        if (self.cs_acceptEventInterval > 0) {
            self.cs_acceptEventTime = [NSDate date].timeIntervalSince1970;
        }
    
        [self cs_sendAction:action to:target forEvent:event];
    }
    
    @end
    

    load方法是在objc库中的一个load_images函数中调用的. 先把二进制映像文件中的头信息取出, 再解析和读出各个模块中的类定义信息, 把实现了load方法的类和Category记录下来, 最后统一执行调用. 主类中的load方法的调用时机要早于Category中的load方法.
    关于load和initialize方法, 可参看博客NSObject的load和initialize方法.
    因此, 我们在Category中的load方法中, 执行runtime的method swizzling, 即可将UIButton的事件响应方法sendAction:to:forEvent:替换为我们自定义的方法cs_sendAction:to:forEvent:.
    关于runtime的关联对象和method swizzling, 这里就不多做介绍了, 可参考博客iOS --- 理解Runtime机制及其使用场景.
    那么, 如何使用呢?

    btn.cs_acceptEventInterval = 1;
    

    这样, 就给UIButton指定了1s的时间间隔用于防止重复点击.

    总结

    三种方式中推荐使用runtime方式, 这样可以为所有的UIButton同时添加.
    有些场景下, 可以考虑使用第二种方式, 自动延迟后以最终的一次点击事件为准执行实际操作.
    Demo请参考DemoRuntime.

  • 相关阅读:
    poj3041(最小顶点覆盖)
    High-speed Charting Control--MFC绘制图表(折线图、饼图、柱形图)控件
    hdu 3183 A Magic Lamp(RMQ)
    Android studio 中创建AIDL Service
    cocos2d-x 3.0正式版 cmd创建project以及一键创建project
    【Machine Learning】决策树案例:基于python的商品购买能力预测系统
    【Machine Learning】机器学习及其基础概念简介
    【Machine Learning】Python开发工具:Anaconda+Sublime
    【HanLP】HanLP中文自然语言处理工具实例演练
    【HanLP】资料链接汇总
  • 原文地址:https://www.cnblogs.com/wangbinios/p/8431693.html
Copyright © 2011-2022 走看看