本文對(duì)原文內(nèi)容進(jìn)行修改
原文 http://www.itdecent.cn/p/d2c2f4aaef0d
項(xiàng)目里有這個(gè)需求,需要對(duì)刪除按鈕進(jìn)行監(jiān)聽,然后做一些自定義的操作。在網(wǎng)上參考了上文的實(shí)現(xiàn)方法,寫了一個(gè)分類,然后前期使用的過程中并未發(fā)現(xiàn)Bug,后來在測(cè)試的時(shí)候,發(fā)現(xiàn)了個(gè)大Bug
Bug:該分類會(huì)監(jiān)聽所有的UITextField 類的deleteBackward函數(shù),如果沒有實(shí)現(xiàn)該分類的代理方法,結(jié)果就是刪除按鈕點(diǎn)了無效!舉個(gè)例子:比如我在A界面想要點(diǎn)擊刪除按鈕自定義事件,然后我實(shí)現(xiàn)了這個(gè)代理,在B頁面我就想使用系統(tǒng)的方法,不想自定義,結(jié)果。在A頁面,確實(shí)是實(shí)現(xiàn)了該效果,在B頁面。。點(diǎn)擊刪除按鈕無效,刪不掉字符了。。。
解決方案:
當(dāng)初始化UITextField的時(shí)候,需要使用 method_exchangeImplementations方法來交換自定義的代理和系統(tǒng)的刪除事件,然后在自定義的代理里面去判斷代理有木有去實(shí)現(xiàn)這個(gè)方法,如果有的話,就執(zhí)行代理事件,否則就把系統(tǒng)的方法和自定義的代理替換回來即可。
具體代碼如下:
頭文件
#import<UIKit/UIKit.h>
@protocol CCTextFieldDelegate
@optional
- (void)textFieldDidDeleteBackward:(UITextField *)textField;
@end
@interface UITextField (Delete)
@property (weak, nonatomic) id delegate;
@end
實(shí)現(xiàn)文件
#import ""UITextField+Delete.h""
#import <objc/runtime.h>
@implementation UITextField (Delete)
- (instancetype)init{
if (self=[super init]) {
Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"deleteBackward"));
Method method2 = class_getInstanceMethod([self class], @selector(cc_deleteBackward));
method_exchangeImplementations(method1, method2);
}
return self;
}
- (void)cc_deleteBackward {
if ([self.delegate respondsToSelector:@selector(textFieldDidDeleteBackward:)])
{
id delegate = (id)self.delegate;
[delegate textFieldDidDeleteBackward:self];
}
else{
Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"deleteBackward"));
Method method2 = class_getInstanceMethod([self class], @selector(cc_deleteBackward));
method_exchangeImplementations(method2, method1);
}
}
@end