Set the maximum character length of a UITextField in Swift
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Limiting the length of a UITextField is a common requirement for usernames, PINs, postal codes, and other structured inputs. The correct implementation should not only stop extra typing, but also handle pasted text and composed characters correctly.
The most reliable UIKit solution is usually the UITextFieldDelegate method shouldChangeCharactersIn. It lets you inspect the proposed new text before the field actually changes.
Use shouldChangeCharactersIn
A basic implementation looks like this:
This method checks what the text would become after the edit and rejects the change if it exceeds the maximum.
Why This Approach Is Better Than Trimming Later
Some code samples wait until editing changed and then cut the text back down. That works, but it can feel less clean to the user because the field briefly accepts too much input and then snaps back.
The delegate approach prevents the invalid change before it lands, which is usually a better fit for constrained fields.
Handle Paste Correctly
The delegate method naturally handles paste operations because the replacement string can contain multiple characters.
For example, if the current text has length 3 and the user pastes 20 characters into a field with max length 10, the method simply rejects the change because the resulting text would be too long.
If you prefer to accept only the allowed prefix of a pasted string rather than reject the whole paste, you can trim manually in an editing-changed handler, but that is a different UX decision.
Be Careful with Unicode Characters
Swift string length is based on user-perceived characters, not raw bytes. That is usually what you want for a character limit.
For example, an emoji may be made of multiple Unicode scalars internally but still count as one visible character. Using String.count matches user-facing expectations much better than lower-level byte counting.
That is one reason the updatedText.count approach is preferable to older NSString-length shortcuts unless your requirement is specifically byte-based.
Reusable Extension Pattern
If you have several text fields with different limits, a delegate helper or small wrapper can keep the code cleaner.
This is useful when multiple fields share the same behavior.
UITextField Length Limits Versus Validation
A length limit is a UI rule, not a full validation strategy. For example, a postal code field may need both:
- a maximum length
- a pattern constraint
So do not treat the character limit as a replacement for final validation when the form is submitted.
Common Pitfalls
One common mistake is using textField.text?.count without applying the proposed replacement range. That fails when the user deletes characters or edits in the middle of the text.
Another issue is using older NSString length logic that counts UTF-16 units rather than user-perceived characters. That can behave poorly with emoji or combined characters.
It is also easy to forget paste behavior. A solution that seems fine for typing may behave badly when a long string is pasted into the field.
Finally, keep in mind that a length limit belongs in the UI and in final validation. A server or model layer should still validate input independently.
Summary
- The usual UIKit solution is
UITextFieldDelegateandshouldChangeCharactersIn. - Calculate the proposed new text and reject edits that exceed the limit.
- This approach handles typing, deletion, and paste events cleanly.
- Swift
String.countis usually the right way to count user-visible characters. - A text-field length limit is useful, but it should not replace final input validation.
Related reading
- Set transparent background of an imageview on Android
- Set UIButton title UILabel font size programmatically
- Set UILabel line spacing
- Set UITableView content inset permanently
- Set up adb on Mac OS X
- Set up adb on Mac OS X
- setBackground vs setBackgroundDrawable Android
- setNeedsLayout vs. setNeedsUpdateConstraints and layoutIfNeeded vs updateConstraintsIfNeeded
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.