iOS监听UITextView、UITextField键盘删除键

UITextView监听删除键:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@""]) {
        /**< 在这里处理删除键的逻辑 */
    }
}

UITextField监听删除键:
UITextField其实里面用的是UIKeyInput,UIKeyInput有一个系统自带的删除方法:

protocol UIKeyInput 

- (BOOL)hasText;
- (void)insertText:(NSString *)text;
- (void)deleteBackward;   <-------就是它删除方法
@end

自定义一个控件继承 UITextField:

.h文件
#import 
@class YNTextField;
@protocol YNTextFieldDelegate 
- (void)ynTextFieldDeleteBackward:(YNTextField *)textField;
@end

@interface YNTextField : UITextField
@property (nonatomic, assign) id  yn_delegate;
@end

.m文件
#import "YNTextField.h"
@implementation YNTextField
- (void)deleteBackward {
    !!!这里要调用super方法,要不然删不了东西
    [super deleteBackward];
    if ([self.yn_delegate respondsToSelector:@selector(ynTextFieldDeleteBackward:)]) {
        [self.yn_delegate ynTextFieldDeleteBackward:self];
    }
}
@end

这样就可以监听UITextField的删除键了

你可能感兴趣的:(iOS监听UITextView、UITextField键盘删除键)