Limiting pasted string length in UITextView or UITextField
Solution 1
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.
Solution 2
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.
Solution 3
Changing the text after it's inserted in textViewDidChange: causes the app to crash if the user presses 'Undo' after the paste.
I played around for quite a bit and was able to get a working solution. Basically the logic is, do not allow the paste if the total length is greater than the max characters, detect the amount that is overflown and insert only the partial string.
Using this solution your pasteboard and undo manager will work as expected.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
NSInteger newLength = textView.text.length - range.length + text.length;
if (newLength > MAX_LENGTH) {
NSInteger overflow = newLength - MAX_LENGTH;
dispatch_async(dispatch_get_main_queue(), ^{
UITextPosition *start = [textView positionFromPosition:nil offset:range.location];
UITextPosition *end = [textView positionFromPosition:nil offset:NSMaxRange(range)];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];
[textView replaceRange:textRange withText:[text substringToIndex:text.length - overflow]];
});
return NO;
}
return YES;
}
Solution 4
This code won't let user to input more characters than maxCharacters. Paste command will do nothing, if pasted text will exceed this limit.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
return newText.count <= maxCharacters;
}
Kevin L.
Developers! Developers! Developers! Developers! Developers! Developers!...DEVELOPERS! DEVELOPERS! DEVELOPERS! DEVELOPERS! DEVELOPERS! DEVELOPERS! DEVELOPERS! DEVELOPERS! YES!
Updated on June 04, 2022Comments
-
Kevin L. almost 2 years
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?
-
Kevin L. almost 15 yearsIn 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...
-
Brad G about 10 yearsThis causes a crash when I 'Undo'. See my answer for a 'slightly' better solution.
-
sam_smith over 9 yearsNot pasting if the text is too long isn't ideal
-
Brad G over 9 yearsThis can be done without the dispatch_async. dispatch_async will cause a crash on iOS8 with the new type ahead feature. I'll rework the code soon.
-
blackjacx about 7 yearsthanks man! this snippet helped me to figure out the correct way of replacing text in a textfield! I made a swift 3 version: gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047
-
bompf over 5 yearsPassing nil as a first argument to
positionFromPosition:offset:
is not allowed. -
Besat over 5 yearsThis create a crash if you hit redo twice. Any change to prevent this crash?Thanks
-
Thao Tran about 3 yearscan you implement it a little bit clearer., like I want the textField always take the firsr 6 letters?
-
Rugmangathan almost 3 years@ThaoTran For taking first six digits you can use
string.prefix(6)
to take first six digits of pasted string inside thestring.length > 1
condition.