Implementation of word limit of uitextview or uitextfield in IOS


Implementation of word limit of uitextview or uitextfield in IOS

The word number limit of uitextview or uitextfield, the limit when entering, and the limit when copying and pasting

There are three ways to limit the number of words

In proxy method

“- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string”


“- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text”

Two methods are implemented in

Method 1 (it can only be restricted when entering, but not when copying and pasting)

if (range.location > MaxCharacterNumber - 1)
  textField.text = [textField.text substringToIndex:MaxCharacterNumber];
  return NO;

Method 2 (both input and copy and paste can be restricted)

NSString *temp = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (temp.length > MaxCharacterNumber)
  textField.text = [temp substringToIndex:MaxCharacterNumber];
  return NO;

In proxy method

“- (void)textViewDidChange:(UITextView *)textView”

A method is implemented in

Method 3 (both copy and paste can be restricted)

NSString *textString = textView.text;
if (textString.length > MaxCharacterNumbers + 1)
  textView.text = [textString substringToIndex:MaxCharacterNumbers];

be careful:

“NSString *temp = [textField.text stringByReplacingCharactersInRange:range withString:string];”

Replace the character range with the specified string and return a new string.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress: recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]