21 监听键盘的删除事件

话不多说,参考了网上的别人的利用runtime交换方法写的UITextfield的分类,直接上代码,复制黏贴即可用!

1.头文件.h

#import 

@protocol JHTextFieldDelegate 

- (void)textFieldDidDeleBackward:(UITextField *)textField;

@end

@interface UITextField (JHTextFiled)
@property(weak,nonatomic) id delegate;
@end

extern NSString *const JHTextFieldDidDeleBackwardNotification;

2.实现文件.m
#import "UITextField+JHTextFiled.h"
#import
NSString *const JHTextFieldDidDeleBackwardNotification = @"JHDeleBackward";
@implementation UITextField (JHTextFiled)
+ (void)load{
Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"deleteBackward"));
Method method2 = class_getInstanceMethod([self class], @selector(JH_deleteBackward));
method_exchangeImplementations(method1, method2);
}
- (void)JH_deleteBackward{
[self JH_deleteBackward];
if ([self.delegate respondsToSelector:@selector(textFieldDidDeleBackward:)]) {
id delegate = (id)self.delegate;
[delegate textFieldDidDeleBackward:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:JHTextFieldDidDeleBackwardNotification object:self];
}
@end
3.在需要的地方添加通知

- (void)viewDidLoad{
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteKeyBoard) name:@"JHDeleBackward" object:nil];
}

4.实现方法

- (void)deleteKeyBoard{
NSLog(@"点击了删除按钮");
//实现需要的业务逻辑即可
}

你可能感兴趣的:(21 监听键盘的删除事件)