iOS-监听键盘删除按钮的点击事件
2018-06-27 本文已影响546人
Simple_Code
核心思想:利用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 {
//删除事件
}