How to limit characters in UITextView iOS

守給你的承諾、 提交于 2019-12-05 22:46:16
Nik

1) add UITextViewDelegate in your viewcontroller like this

@interface ViewController : UIViewController <UITextViewDelegate>

Each time a user types a character on the keyboard, just before the character is displayed,following method get called. This is a handy location to test the characters that a user is typing and disallow specific characters you want to restrict.

textView:shouldChangeCharactersInRange:replacementString

2) then write following code. instead of 140 you can put whatever number you want.

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

For more help take a look at UItextView

Swift 2.0 solution

 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    return textView.text.characters.count + (text.characters.count - range.length) <= textViewLimit
}

Try this

 - (BOOL)isAcceptableTextLength:(NSUInteger)length {
    return length <= 70;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string {
    return [self isAcceptableTextLength:textField.text.length + string.length - range.length];
}

-(IBAction)checkIfCorrectLength:(id)sender{
    if (![self isAcceptableTextLength:self.textField.text.length]) {
        // do something to make text shorter
    }
}

you can use below code to restrict textview characters in first method you can set restricted length for textfield or if you past text which is more than your restricted text it will create substring of that string to fix length for textview.

#pragma mark - Textview Delegate
 -(void)textViewDidChange:(UITextView *)textView
 {   
    NSString *temp = textView.text;
   titleLength = textView.text.length;
   if (titleLength > RESTRICTED_LENGHT ) 
    {
    textView.text = [temp substringToIndex:RESTRICTED_LENGHT];
    }
 }

or you can use this delegate method and return No if text view text length is greater than your restricted length.

 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
     if([text length] == 0)
      {
        if([textView.text length] != 0)
        {
          return YES;
        }
     }
   else if([[textView text] length] > 139)
    {
       return NO;
    }
   return YES;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!