Search code examples
iosuitextviewuitextviewdelegate

limit number of characters user may enter into multiple UITextViews


In some sense this question has already been answered at Limit number of characters in uitextview. But my particular case is that I have more than one textview in the same ViewController. So I am not sure how to fix that problem. Say I only have two textViews. How might I handle these cases:

  • they both have the same character limit?

  • each has different character limit? say 300 and 400 respectively.

Do I use IBAction? If yes how?


Solution

  • So you need IBOutlet for both textviews

    @property (weak, nonatomic) IBOutlet UITextField *textfield1;
    @property (weak, nonatomic) IBOutlet UITextField *textfield2;
    

    then in your delegate method

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    

    You simply add a check for the right textfield

    if (self.textfield1 == textfield) {
    // handle first text field here
    
    } else {
    // handle second text field here
    }