您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页iOS 拦截所有按钮的点击事件

iOS 拦截所有按钮的点击事件

来源:二三娱乐

引言

项目中,经常会使用runtime来做一下事项:

1、在程序运行过程中,动态的创建类,动态添加、修改这个类的属性和方法;

2、遍历一个类中所有的成员变量、属性、以及所有方法

3、消息传递、转发

例如:
1、防数组越界使用拦截数组的objectAtIndex:方法
2、给所有ViewController添加统计代码的时候拦截所有ViewController的viewWillAppear:方法和viewWillDisappear:方法。

解决办法

为UIButton添加一个分类,分类中将按钮点击事件进行替换,在替换的方法中判断,可以选择的去执行自定义的方法, 或者正常走按钮的点击事件。

代码如下:

#import <UIKit/UIKit.h>

@interface UIButton (lmyClickAction)

@end


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

@implementation UIButton (lmyClickAction)

+ (void)load{

    [super load];

//拿到sendAction方法,
    Method oldObjectAtIndex =class_getInstanceMethod([UIButton class],@selector(sendAction:to:forEvent:));

//定义一个新的方法custom_sendAction
    Method newObjectAtIndex =class_getInstanceMethod([UIButton class], @selector(custom_sendAction:to:forEvent:));

//交换两个方法的指针
    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);

}

- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    [super sendAction:action to:target forEvent:event];
}

- (void)custom_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    
    if (1==1) {
        NSLog(@"自定义方法");
    }else{
        [self custom_sendAction:action to:target forEvent:event];
//调用custom_sendAction方法,其实指针是指向的原来的sendAction方法
    }
}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务