引出
我们在写APP时有时需要查看是否调用了该方法,而对于系统自带的UI控件,我们一般无法修改其方法或者修改之后会不按照你的想法运行,这时我们就想自己去写一个方法去替换它
方法
例如我们想修改UIView的 hitTest:withEvent: 方法,得创建一个UIView的分类,这里我叫ChangeMethod
先自己将要实现的方法写好,然后使用Runtime运行时方法 method_exchangeImplementations 交换
#import "UIView+ChangeMethod.h"
#import <objc/runtime.h>
@implementation UIView (ChangeMethod)
+ (void)load {
Method origin = class_getInstanceMethod([UIView class], @selector(hitTest:withEvent:));
Method custom = class_getInstanceMethod([UIView class], @selector(tay_hitTest:withEvent:));
method_exchangeImplementations(origin, custom);
origin = class_getInstanceMethod([UIView class], @selector(pointInside:withEvent:));
custom = class_getInstanceMethod([UIView class], @selector(tay_pointInside:withEvent:));
method_exchangeImplementations(origin, custom);
}
- (UIView *)tay_hitTest:(CGPoint)point withEvent:(UIEvent *)event {
NSLog(@"%@ hitTest", NSStringFromClass([self class]));
UIView *result = [self tay_hitTest:point withEvent:event];
NSLog(@"%@ hitTest return: %@", NSStringFromClass([self class]), NSStringFromClass([result class]));
return result;
}
- (BOOL)tay_pointInside:(CGPoint)point withEvent:(UIEvent *)event {
NSLog(@"%@ pointInside", NSStringFromClass([self class]));
BOOL result = [self tay_pointInside:point withEvent:event];
NSLog(@"%@ pointInside return: %@", NSStringFromClass([self class]), result ? @"YES":@"NO");
return result;
}
注意:我们一般修改系统自带方法只是为了添加打印,还是需要执行原方法的。而在我们自己写的方法里,因为已经交换了,tay_hitTest: withEvent: 也就是原方法