views:

1873

answers:

3

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

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?

A: 

One of the answers in the first question you linked above to should work, namely using something like

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitTextField:) name:@"UITextFieldTextDidChangeNotification" object:myTextField];

to watch for changes to the text in the UITextField and shorten it when appropriate.

David Maymudes
In this special case, conforming to the UITextViewDelegate (or UITextFieldDelegate) is preferable to rolling your own notification (and easier to debug). And I should probably post how I actually pulled this issue off...
Kevin L.
+2  A: 

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.

Kevin L.
+3  A: 

In my experience just implementing the delegate method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

works with pasting. The entire pasted string comes across in the replacementString: argument. Just check it's length, and if it's longer than your max length, then just return NO from this delegate method. This causes nothing to be pasted. Alternatively you could substring it like the earlier answer suggested, but this works to prevent the paste at all if it's too long, if that's what you want.

Rob