Restrict the user to enter max 50 words in UITextView iOS

对着背影说爱祢 提交于 2019-12-08 07:24:53

问题


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.



来源:https://stackoverflow.com/questions/20515131/restrict-the-user-to-enter-max-50-words-in-uitextview-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!