NEW: Learn SwiftUI with my free YouTube video series! >>

How to limit the number of characters in a UITextField or UITextView

Swift version: 5.0

Paul Hudson    @twostraws   

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).

Next, add one of these two methods, depending on whether you are working with text fields (single line) or text views (multiple lines):

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }

    let updatedText = currentText.replacingCharacters(in: stringRange, with: string)

    return updatedText.count <= 16
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let currentText = textView.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }

    let changedText = currentText.replacingCharacters(in: stringRange, with: text)

    return changedText.count <= 16
}

I've specified 16 as the maximum number of characters, but just change that to whatever you need.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

Available from iOS 7.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>