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?
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).
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With