项目中遇到这么一个问题,需要对用户昵称长度做限制,起初没想太多,那就直接在UITextFieldDelegate的一个协议中做就OK啊,协议如下:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
我自己在模拟器上是可以的,后来测试给我报个bug,说不行,我仔细看其操作,他用了联想输入,还用了第三方输入法。。。确实不行,好吧,看来这个协议是不行的,就想着监听呗,监听这个UITextField,代码如下:
首先在ViewDidLoad方法中注册通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:) name:UITextFieldTextDidChangeNotification object:self.textField];
然后实现selector方法
- (void)textFieldEditChanged:(NSNotification *)obj {
UITextField *textField = (UITextField *)obj.object;
NSString *toBeString = textField.text;
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
if (!position || !selectedRange) {
if (toBeString.length > MaxTextFieldTextLength) {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"昵称长度不能超过30个字符" preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
}];
[alertVC addAction:action];
[self presentViewController:alertVC animated:YES completion:nil];
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MaxTextFieldTextLength];
if (rangeIndex.length == 1) {
textField.text = [toBeString substringToIndex:MaxTextFieldTextLength];
}else {
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MaxTextFieldTextLength)];
textField.text = [toBeString substringWithRange:rangeRange];
}
}
}
}