项目需求:UITextField和UITextView长按文字只能出现选择、全选、拷贝、粘贴选项
用runtime实现,给UITextField和UITextView写个分类,重写load方法,替换系统canPerformAction:withSender:方法
@implementation UITextField (zxh)
+(void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_canPerformAction:withSender:"));
Method m2 = class_getInstanceMethod(self, NSSelectorFromString(@"canPerformAction:withSender:"));
method_exchangeImplementations(m1, m2);
});
}
-(BOOL)zxh_canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(select:))
{
return YES;
}
else if (action == @selector(selectAll:))
{
return YES;
}
else if (action == @selector(copy:))
{
return YES;
}
else if (action == @selector(paste:))
{
return YES;
}
else{
return NO;
}
}
@end
@implementation UITextView (zxh)
+(void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_canPerformAction:withSender:"));
Method m2 = class_getInstanceMethod(self, NSSelectorFromString(@"canPerformAction:withSender:"));
method_exchangeImplementations(m1, m2);
});
}
-(BOOL)zxh_canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(select:))
{
return YES;
}
else if (action == @selector(selectAll:))
{
return YES;
}
else if (action == @selector(copy:))
{
return YES;
}
else if (action == @selector(paste:))
{
return YES;
}
else{
return NO;
}
}
@end
网友评论