完全解决快速连续多次点击button导致跳转多个界面(注:方法从他人博客中看到,稍作修改)

在实际开发过程中,由于我们在点击一个button后进行网络请求,然后进行页面的跳转,但是当网络较慢,但是一直连续点击button,造成跳转一个页面多次,虽有通过button的enable可以稍作解决,但是不能根本解决,通过其他人的博客看到一个很好的方法,稍作修改,贡献出来。感谢大家的奉献!!!!

1.自定义一个myButton类继承UIButton


  .h文件

#import <UIKit/UIKit.h>

@interface myButton : UIButton

@property(nonatomic,assign) NSTimeInterval uxy_acceptEventInterval;// 可以用这个给重复点击加间隔

@property(nonatomic,assign)BOOL uxy_ignoreEvent;

@end


.m文件


#import "myButton.h"

#import <objc/runtime.h>

@implementation myButton

static 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);

}


+ (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);

}


- (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];

}


@end


2. 在要用到的地方按此应用,打印点击的时间,你会发现问题解决了,点击的时间间隔随你设置


#import "ViewController.h"

#import "myButton.h"

@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor =[UIColor whiteColor];

    

    myButton *btn = [[myButton alloc] initWithFrame:CGRectMake(30, 150, 200, 50)];

    btn.backgroundColor = [UIColor redColor];

    btn.uxy_acceptEventInterval= 1.0;//设置点击的时间间隔

    btn.uxy_ignoreEvent = NO;

    [btn addTarget:self action:@selector(djfdfj) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

    

}


- (void)djfdfj

{

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

    [forma setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *dateStr = [forma stringFromDate:[NSDate date]];

    NSLog(@"%@",dateStr);

    

    

}

@end


3.完美解决button的连续点击问题,,谢谢大家阅读!!!!!!!!!!!!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值