iOS UIButton之防止重复点击(控制事件响应时间间隔)


有几个实际业务场景需要控制UIButton响应事件的时间间隔。比如:
1、当通过点击按钮来执行网络请求时,若请求耗时稍长,用户往往会再点一次。这样,就执行了两次请求,造成了资源浪费。
2、在移动终端性能较差时(比如iPhone 6升级到iOS 11😅),连续点击按钮会执行多次事件(比如push出来多个viewController)。
3、防止暴力点击。

控制按钮响应事件时间间隔的方案不止一种。比如:

  • 方案 1:通过UIButtonenabled属性和userInteractionEnabled属性控制按钮是否可点击。此方案在逻辑上比较清晰、易懂,但具体代码书写分散,常常涉及多个方法。
- (void)buttonClicked:(UIButton *)sender { sender.enabled = NO; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ sender.enabled = YES; }); } 
  • 方案2:通过NSObject的+cancelPreviousPerformRequestsWithTarget:selector:object:方法和-performSelector:withObject:afterDelay:方法控制按钮的响应事件的执行时间间隔。此方案会在连续点击按钮时取消之前的点击事件,从而只执行最后一次点击事件,会出现延迟现象。
- (void)buttonClicked:(UIButton *)sender { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClickedAction:) object:sender]; [self performSelector:@selector(buttonClickedAction:) withObject:sender afterDelay:2.0]; } 

在需要对大量UIButton做控制的场景中,方案1和方案2会比较不方便。针对此场景,着重说一下方案3。

  • 方案3:通过Runtime控制UIButton响应事件的时间间隔。思路如下:
    1、创建一个UIButton的类别,使用runtimeUIButton增加public属性qi_eventIntervalprivate属性eventUnavailable
    2、在+load方法中使用runtimeUIButton-sendAction:to:forEvent:方法与自定义的-qi_sendAction:to:forEvent:方法交换Implementation
    3、使用qi_eventInterval作为控制eventUnavailable的计时因子,用eventUnavailable开控制UIButtonevent事件是否有效。

方案3可以对所有UIButton生效,具体实现代码如下:

@interface UIButton (QiEventInterval) @property (nonatomic, assign) NSTimeInterval qi_eventInterval; @end 
#import "UIButton+QiEventInterval.h" #import <objc/runtime.h> static char * const qi_eventIntervalKey = "qi_eventIntervalKey"; static char * const eventUnavailableKey = "eventUnavailableKey"; @interface UIButton () @property (nonatomic, assign) BOOL eventUnavailable; @end @implementation UIButton (QiEventInterval) + (void)load { Method method = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:)); Method qi_method = class_getInstanceMethod(self, @selector(qi_sendAction:to:forEvent:)); method_exchangeImplementations(method, qi_method); } #pragma mark - Action functions //- (void)qi_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event { // if (self.eventUnavailable == NO) { // self.eventUnavailable = YES; // [self qi_sendAction:action to:target forEvent:event]; // [self performSelector:@selector(setEventUnavailable:) withObject:@(NO) afterDelay:self.qi_eventInterval]; // } //} - (void)qi_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event { if([self isMemberOfClass:[UIButton class]]) { if (self.eventUnavailable == NO) { self.eventUnavailable = YES; [self qi_sendAction:action to:target forEvent:event]; [self performSelector:@selector(setEventUnavailable:) withObject:0 afterDelay:self.qi_eventInterval]; } } else { [self qi_sendAction:action to:target forEvent:event]; } } #pragma mark - Setter & Getter functions - (NSTimeInterval)qi_eventInterval { return [objc_getAssociatedObject(self, qi_eventIntervalKey) doubleValue]; } - (void)setQi_eventInterval:(NSTimeInterval)qi_eventInterval { objc_setAssociatedObject(self, qi_eventIntervalKey, @(qi_eventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (BOOL)eventUnavailable { return [objc_getAssociatedObject(self, eventUnavailableKey) boolValue]; } - (void)setEventUnavailable:(BOOL)eventUnavailable { objc_setAssociatedObject(self, eventUnavailableKey, @(eventUnavailable), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end 


使用方法:

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
/* here is some button's configuration codes */
[self.view addSubview:button];
    
//! 设置按钮的点击响应间隔时间
button.qi_eventInterval = 2.0;


效果展示:

  • 默认Button点击效果:



     
    不设置qi_eventInterval (默认为0)
  • 设置qi_eventInterval为2秒:



     
    设置qi_eventInterval为2秒 

PS:针对方案3,因为在UIButton+QiEventInterval.m中的+load方法中交换了UIControlsendAction:to:forEvent:方法,所以在使用UIControl或其子类(比如UISlider)的sendAction:to:forEvent:方法时会引起参数缺失的崩溃。可以将UIButton+QiEventInterval改成UIControl+QiEventInterval以避免此问题。

可从Github获取工程源码


关注我们的途径有:
QiShare(简书)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公众号)

推荐文章:iOS UIButton之UIEdgeInsets详解

iOS 计算时间差   避免过度使用定时器

  (2017-12-13 19:49:46)
   
代码繁琐,先做笔记,有时间进行优化
 

 NSString *recordDate = [[NSUserDefaultsstandardUserDefaults]objectForKey:@"recordDate"];

    

    if (recordDate.length != 0) {

    

        NSDate *nowDate = [NSDate date]; // 当前时间

    

        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

        

        [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];

        

        NSString*timeString=[formatter stringFromDate: nowDate];

      

        double timeDiff = 0.0;

        

        NSDateFormatter *formatters = [[NSDateFormatter alloc]init];

        [formatters setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];

        NSDate *dateS = [formatters dateFromString:recordDate];

        

        NSDateFormatter *formatterE = [[NSDateFormatter alloc]init];

        [formatterE setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];

        NSDate *dateE = [formatterE dateFromString:timeString];

        

        timeDiff = [dateE timeIntervalSinceDate:dateS ];

        int myInt = (int)timeDiff;

        if (myInt < 20) {

           

            MBProgressHUD *hud = [[MBProgressHUD alloc] init];

            [self.view addSubview:hud];

            hud.labelText = @"请勿频繁操作";//@"网络连接失败";

            hud.mode = MBProgressHUDModeText;

            [hud showAnimated:YES whileExecutingBlock:^{

                sleep(1);

            } completionBlock:^{

                [hud removeFromSuperview];

            }];

            return;

           

        }

  

    }

 

 

 

#pragma mark-保存本地时间到沙盒

-(void)currentDateString{

    

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    

    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];

    

    NSString*timeString=[formatter stringFromDate: [NSDate date]];

    

//    NSDate *currentDate = [NSDate date];

//    NSString *currentDateString = [NSString stringWithFormat:@"%ld", (long)[currentDate timeIntervalSince1970]];

    [[NSUserDefaults standardUserDefaults] setObject:timeStringforKey:@"recordDate"];

    [[NSUserDefaults standardUserDefaults] synchronize];

 

}

 

作者:QiShare
链接:https://www.jianshu.com/p/c2243ac4f620
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM