iOS 程式碼限制textField的輸入長度並且刪除按鈕還得有效

weixin_34365417發表於2018-01-17

通常,我們在開發一個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;
}

原文地址:http://blog.csdn.net/u010217380/article/details/50275325

相關文章