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.

Community
  • 1
  • 1
iOSAppDev
  • 2,755
  • 4
  • 39
  • 77
  • 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 ? – Nikhil Mathew Dec 11 '13 at 10:23

3 Answers3

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;
    }
Nikos M.
  • 13,685
  • 4
  • 47
  • 61
Maulik Kundaliya
  • 452
  • 3
  • 17
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.

Gauntlet
  • 141
  • 3
  • 9
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.

payal
  • 162
  • 7
  • You should read question carefully. Don't lead to confusion with correct answer of other question. – Mani Dec 11 '13 at 09:42