实时监控UITextField的输入长度,包括联想字符
程序员文章站
2022-04-06 08:21:54
...
由于限制UITextField的长度的时候,不能限制联想字符,解决方案如下:
在viewDidLoad方法中注册Observer:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:@"UITextFieldTextDidChangeNotification" object:_textFieldName];
在dealloc方法中移除Observer:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:_textFieldName];
然后实现下面的代理方法
- (void)textFieldDidChange:(NSNotification *)notification{
UITextField *textField = (UITextField *)notification.object;
if (textField == _textFieldName) {
NSUInteger wordLen = textField.text.length;
if (wordLen > 19) {
textField.text = [textField.text substringToIndex:19];
wordLen = 19;
}
}
}