English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Limiting the Input Length of TextField with Only a Few Lines of iOS Code

There are many methods to limit the input length of textField on the internet, but I think none of them are very perfect. To be more accurate, they can be said to be not in line with the requirements of actual development, so I will summarize the methods to limit the input length of textField here.

 The method I use is not the listening method but the most different delegate implementation method, why not use the listening method?63;63;63;
 If you see this article, you might be troubled by one thing, that is, after using the listening to limit the input length, you cannot control the input content perfectly.

 Let's take a simple example: 

You want to limit the input length to30 characters, when you enter30 characters after listening can control you from entering more, but problems also arise, when you move the cursor to the middle of the input content, you can continue to enter. This kind of input is very annoying because after you enter, your cursor will move to the end, and you will be restricted from entering more, but the content you just entered will remain in the middle of the text, which is very inconsistent with the requirements.

 Therefore, using the delegate here can achieve the effect we want very well, just a few lines of code, I hope it can help you.

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  if (textField == self.liveThemeTextField) {
  //The if here is to get the delete operation, without this if, it would cause the consequence that the delete key cannot be used after reaching the word limit.
    if (range.length == 1 && string.length == 0) {
      return YES;
    }
    //so easy
    else if (self.liveThemeTextField.text.length >= 30) {
      self.liveThemeTextField.text = [textField.text substringToIndex:30];
      return NO;
    }
  }
  return YES;
}

That's all for this article, I hope it helps with your learning, and I also hope everyone will support the Yell Tutorial.

You May Also Like