UITextField
iOS Development
Character Limit
Swift Programming
Mobile App Development

Set the maximum character length of a UITextField

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The standard way to limit the length of a UITextField is to intercept edits in textField(_:shouldChangeCharactersIn:replacementString:) and reject changes that would exceed the limit. The implementation looks simple, but it should account for replacement ranges, paste operations, and Swift string indexing correctly.

Use the Text Field Delegate

Set a delegate and implement the edit decision method.

swift
1import UIKit
2
3final class ViewController: UIViewController, UITextFieldDelegate {
4    @IBOutlet private weak var textField: UITextField!
5    private let maxLength = 10
6
7    override func viewDidLoad() {
8        super.viewDidLoad()
9        textField.delegate = self
10    }
11
12    func textField(_ textField: UITextField,
13                   shouldChangeCharactersIn range: NSRange,
14                   replacementString string: String) -> Bool {
15        guard let currentText = textField.text,
16              let textRange = Range(range, in: currentText) else {
17            return true
18        }
19
20        let updatedText = currentText.replacingCharacters(in: textRange, with: string)
21        return updatedText.count <= maxLength
22    }
23}

This version handles insertion, deletion, replacement, and paste with the same logic.

Why the Range Conversion Matters

A lot of examples online use currentText.count + string.count - range.length, which looks fine for simple ASCII input. The safer Swift approach is to convert the NSRange into a Swift Range and build the updated string directly.

That matters because Swift strings are Unicode-correct and do not map cleanly to simple byte or UTF-16 length assumptions in every case.

Pasting Text Should Respect the Same Limit

A character limit should apply to typing and pasting the same way. The delegate method above already handles both, because paste arrives as a replacement string too.

If you want to truncate pasted text instead of rejecting it entirely, you can modify the text manually.

swift
1func textField(_ textField: UITextField,
2               shouldChangeCharactersIn range: NSRange,
3               replacementString string: String) -> Bool {
4    guard let currentText = textField.text,
5          let textRange = Range(range, in: currentText) else {
6        return true
7    }
8
9    let updatedText = currentText.replacingCharacters(in: textRange, with: string)
10    if updatedText.count <= maxLength {
11        return true
12    }
13
14    textField.text = String(updatedText.prefix(maxLength))
15    return false
16}

That behavior is a product decision. Some apps prefer hard rejection, others prefer automatic clipping.

Character Count Is Not Always User-Perceived Length

Emoji and combined characters complicate the idea of length. Swift’s count works on extended grapheme clusters, which is usually what you want for user-facing limits. That is one more reason to avoid simplistic byte-length math.

If your backend has a byte limit rather than a visible-character limit, validate that separately.

Keep Validation Consistent with the Rest of the App

A UI text limit is only one layer of validation. If the same field is saved to a server or local database, make sure the same or stricter constraint exists there too. Otherwise, the UI and persistence rules can drift apart and create confusing bugs.

Client-side limits improve experience. They should not be the only enforcement point.

Common Pitfalls

  • Using naive length arithmetic instead of building the updated Swift string correctly.
  • Forgetting that paste operations should be subject to the same limit as typing.
  • Ignoring Unicode behavior and assuming every visible character maps to one simple unit.
  • Enforcing the limit only in the UI while backend or storage rules differ.
  • Rejecting edits without giving the product team a clear decision about truncation versus hard stop behavior.

Summary

  • Use UITextFieldDelegate to enforce a maximum character length.
  • Convert NSRange into a Swift Range and evaluate the actual updated text.
  • The same delegate logic handles typing, deletion, and paste.
  • Use Swift string counting for user-visible character limits.
  • Keep UI limits aligned with backend and storage validation rules.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.