通常,我们在开发一个app时登录组册界面均为textField的输入。然而,我们的手机号及验证码的位数是固定的,那我我们就有必要限制textField的输入字符串的长度,通常的做法如下:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField isEqual:self.phoneNumberTextField]) {
return textField.text.length < 11;
}
else if ([textField isEqual:self.verificationCodeTextField]) {
return textField.text.length < 6;
}
else if ([textField isEqual:self.passwordTextField]) {
return textField.text.length < 16;
}
return YES;
}
如果我们按照上面的方式写的话,当我们的手机号输入11位之后,键盘的删除按钮就失效了,但,只要改成下面这样就可以了:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (range.length == 1 && string.length == 0) {
return YES;
}
else if ([textField isEqual:self.phoneNumberTextField]) {
return textField.text.length < 11;
}
else if ([textField isEqual:self.verificationCodeTextField]) {
return textField.text.length < 6;
}
else if ([textField isEqual:self.passwordTextField]) {
return textField.text.length < 16;
}
return YES;
}
有没有帮到你呢?
网友评论