Restrict the user to enter max 50 words in UITextV

2019-06-06 12:31发布

问题:

I am trying to restrict the user to enter max 50 words in UITextView. I tried solution by PengOne from this question1 . This works for me except user can enter unlimited chars in the last word.

So I thought of using regular expression. I am using the regular expression given by VonC in this question2. But this does not allow me enter special symbols like , " @ in the text view.

In my app , user can enter anything in the UITextView or just copy-paste from web page , notes , email etc.

Can anybody know any alternate solution for this ?

Thanks in advance.

回答1:

This code should work for you.

  - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
        return textView.text.length + (text.length - range.length) <= 50;
    }


回答2:

Do as suggested in "question2", but add @ within the brackets so that you can enter that as well. May need to escape it if anything treats it as a special character.



回答3:

You use [NSCharacterSet whitespaceCharacterSet] to calculate word.

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
static const NSUInteger MAX_NUMBER_OF_LINES_ALLOWED = 3;

NSMutableString *t = [NSMutableString stringWithString: self.textView.text];
[t replaceCharactersInRange: range withString: text];

NSUInteger numberOfLines = 0;
for (NSUInteger i = 0; i < t.length; i++) {
    if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember: [t characterAtIndex: i]]) {
        numberOfWord++;
    }
}

return (numberOfWord < 50);
}

The method textViewDidChangeSelection: is called when a section of text is selected or the selection is changed, such as when copying or pasting a section of text.