Only a few lines of iOS code limit the TextField input length

  • 2020-11-25 07:35:47
  • OfStack

There are many ways to limit the length of textField input on the Internet, but I don't think they are perfect or exactly meet the requirements of the actual development. Therefore, the methods of textField to limit the length of input are summarized here.

Instead of listening, I use the most different proxy implementation. Why not use listening? The & # 63; The & # 63;
When you read this article, it's likely that you'll find one thing that bothers you is that you won't be able to control the input perfectly by using monitoring to limit the length of the input.

Take a simple example:

You to limit input to 30 characters in length, when you enter the 30 characters after listening can indeed good control won't let you continue to enter, but the problem is, when you move the cursor to a location in the middle of the input, you can continue to input the input to let a person very upset because when you input your cursor will move to the end, and limit you continue to enter, but you just typed in glory is retained in the middle of the text, which is not conform to the requirements.

So using agents here is a good way to achieve what we want, just a few lines of code to help you.


 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  
  if (textField == self.liveThemeTextField) {
  // Here, if Time to get the delete operation , If there is no time if This will result in the deletion of the key that cannot be used when the word limit is reached .
    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;
}

Related articles: