How shouldChangeCharactersInRange works in Swift?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
shouldChangeCharactersIn range: is a UITextFieldDelegate method that is called every time the user types, deletes, or pastes text into a UITextField. It gives you the opportunity to inspect the proposed change and either allow or reject it by returning true or false. This is the primary mechanism for input validation, character limiting, and text formatting in iOS text fields.
Method Signature
Parameters
textField: The text field that is being edited.range: AnNSRangeindicating which characters in the current text will be replaced. For a simple insertion,range.lengthis 0. For a deletion,stringis empty.string: The replacement string. This is the text being typed or pasted. For a backspace, this is an empty string"".
Return Value
true: Allow the replacement to occur.false: Reject the change — the text field remains unchanged.
Understanding the Parameters
Computing the Resulting Text
To see what the text would look like after the change:
Common Use Cases
Character Limit
Restrict the text field to a maximum number of characters:
Numbers Only
Allow only numeric input:
Phone Number Formatting
Auto-format as the user types:
Decimal Input (Max 2 Decimal Places)
Disabling Paste
NSRange vs Swift Range
A critical detail: the range parameter is an NSRange, which works with UTF-16 code units (Objective-C NSString). Swift strings use Unicode scalars. For strings with emoji or non-ASCII characters, you must convert properly:
Common Pitfalls
- Returning false but not updating text: If you return
falseto apply custom formatting (like the phone number example), you must settextField.textyourself. Returningfalsewithout setting the text means no change occurs. - NSRange/Swift Range mismatch: Always use
Range(range, in: currentText)to convert. Direct NSRange subscripting on Swift strings causes crashes with emoji, accented characters, or CJK text. - Not handling paste: When the user pastes,
stringcontains the entire pasted content. If you only validate single characters, pasted text may bypass your validation. - Cursor position after manual text update: When you set
textField.textmanually and returnfalse, the cursor jumps to the end. To maintain cursor position, usetextField.selectedTextRange. - Combine with
editingChanged: For real-time validation UI (enabling/disabling a button), also listen to the.editingChangedcontrol event, asshouldChangeCharactersInfires before the change happens.
Summary
shouldChangeCharactersIn range:is called before every text change — returntrueto allow,falseto reject- Use
Range(range, in: currentText)to safely convert NSRange to Swift Range - Compute the resulting text with
replacingCharacters(in:with:)to make validation decisions - For custom formatting, set
textField.textmanually and returnfalse - Always handle empty
string(backspace) and multi-characterstring(paste)
Related reading
- How to access Activity.this in Kotlin?
- How to access data/data folder in Android device?
- How to access iOS simulator camera
- How to access safe area size in SwiftUI?
- How to access SOAP services from iPhone
- How to add 2 buttons into the UINavigationbar on the right side without IB?
- How to add a border just on the top side of a UIView
- How to add a button to UINavigationBar?
.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.