Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting pasted string length in UITextView or UITextField

The problem of limiting strings that are directly entered into a UITextView or UITextField has been addressed on SO before:

  • iPhone SDK: Set Max Character length TextField
  • iPhone sdk 3.0 issue

However now with OS 3.0 copy-and-paste becomes an issue, as the solutions in the above SO questions don’t prevent pasting additional characters (i.e. you cannot type more than 10 characters into a field that is configured with the above solutions but you can easily paste 100 characters into the same field).

Is there a means of preventing directly entered string and pasted string overflow?

like image 743
Kevin L. Avatar asked Jul 16 '09 06:07

Kevin L.


People also ask

How do I limit the number of characters in UITextField or UITextView?

If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).

How do I restrict UITextField to take only numbers in Swift?

Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.

How check textField is empty or not in Swift?

storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label. @IBOutlet weak var textField: UITextField! @IBOutlet weak var resultLabel: UILabel!


1 Answers

I was able to restrict entered and pasted text by conforming to the textViewDidChange: method within the UITextViewDelegate protocol.

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length >= 10)
    {
        textView.text = [textView.text substringToIndex:10];
    }
}

But I still consider this kind of an ugly hack, and it seems Apple should have provided some kind of "maxLength" property of UITextFields and UITextViews.

If anyone is aware of a better solution, please do tell.

like image 161
Kevin L. Avatar answered Nov 15 '22 20:11

Kevin L.