美文网首页iOS开发-键盘
iOS-监听键盘删除按钮的点击事件

iOS-监听键盘删除按钮的点击事件

作者: Simple_Code | 来源:发表于2018-06-27 09:51 被阅读546次

    核心思想:利用Runtime动态替换方法,拦截deleteBackward方法实现自定义代理
    具体看下面代码

    #import <UIKit/UIKit.h>
    
    @protocol SPTextFieldDelegate <UITextFieldDelegate>
    @optional
    - (void)textFieldDidDeleteBackward:(UITextField *)textField;
    @end
    
    @interface UITextField (SPExtension)
    @property (weak, nonatomic) id<SPTextFieldDelegate> delegate;
    @end
    /**
     *  监听删除按钮
     *  object:UITextField
     */
    extern NSString * const SPTextFieldDidDeleteBackwardNotification;
    
    #import "UITextField+SPExtension.h"
    #import <objc/runtime.h>
    
    NSString * const SPTextFieldDidDeleteBackwardNotification = @"textfield_did_notification";
    
    @implementation UITextField (SPExtension)
    
    + (void)load {
        Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"deleteBackward"));
        Method method2 = class_getInstanceMethod([self class], @selector(sp_deleteBackward));
        method_exchangeImplementations(method1, method2);
    }
    - (void)sp_deleteBackward {
        [self sp_deleteBackward];
        
        if ([self.delegate respondsToSelector:@selector(textFieldDidDeleteBackward:)])
        {
            id <SPTextFieldDelegate> delegate  = (id<SPTextFieldDelegate>)self.delegate;
            [delegate textFieldDidDeleteBackward:self];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:SPTextFieldDidDeleteBackwardNotification object:self];
    }
    @end
    

    在使用的文件中遵循SPTextFieldDelegate代理,代理的方法即为点击删除按钮事件:

    - (void)textFieldDidDeleteBackward:(UITextField *)textField {
        //删除事件
    }
    

    相关文章

      网友评论

        本文标题:iOS-监听键盘删除按钮的点击事件

        本文链接:https://www.haomeiwen.com/subject/hptbyftx.html