Restrict the user to enter max 50 words in UITextView iOS
Asked Answered
E

3

1

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.

Ethmoid answered 11/12, 2013 at 9:20 Comment(1)
You said answer to question1 works for you "except user can enter unlimited chars in the last word". Well if you are setting only a word limitation, any word can be of any length. You will need to set both a word limit and a word length limit. Is that what you want ?Phalan
D
3

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;
    }
Datura answered 11/12, 2013 at 9:27 Comment(1)
words, not charactersBoycie
B
0

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.

Bloodthirsty answered 11/12, 2013 at 9:33 Comment(0)
C
0

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.

Covet answered 11/12, 2013 at 9:40 Comment(1)
You should read question carefully. Don't lead to confusion with correct answer of other question.Sixpenny

© 2022 - 2024 — McMap. All rights reserved.