監(jiān)聽UITextField的刪除事件(完善)

本文對(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容