话不多说,参考了网上的别人的利用runtime交换方法写的UITextfield的分类,直接上代码,复制黏贴即可用!
1.头文件.h
#import <UIKit/UIKit.h>
@protocol JHTextFieldDelegate <NSObject>
- (void)textFieldDidDeleBackward:(UITextField *)textField;
@end
@interface UITextField (JHTextFiled)
@property(weak,nonatomic) id<JHTextFieldDelegate> delegate;
@end
extern NSString *const JHTextFieldDidDeleBackwardNotification;
2.实现文件.m
#import "UITextField+JHTextFiled.h"
#import <objc/runtime.h>
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<JHTextFieldDelegate> delegate = (id<JHTextFieldDelegate>)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(@"点击了删除按钮");
//实现需要的业务逻辑即可
}