Max length UITextField Max length UITextField ios ios

Max length UITextField


With Swift 5 and iOS 12, try the following implementation of textField(_:shouldChangeCharactersIn:replacementString:) method that is part of the UITextFieldDelegate protocol:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {    guard let textFieldText = textField.text,        let rangeOfTextToReplace = Range(range, in: textFieldText) else {            return false    }    let substringToReplace = textFieldText[rangeOfTextToReplace]    let count = textFieldText.count - substringToReplace.count + string.count    return count <= 10}
  • The most important part of this code is the conversion from range (NSRange) to rangeOfTextToReplace (Range<String.Index>). See this video tutorial to understand why this conversion is important.
  • To make this code work properly, you should also set the textField's smartInsertDeleteType value to UITextSmartInsertDeleteType.no. This will prevent the possible insertion of an (unwanted) extra space when performing a paste operation.

The complete sample code below shows how to implement textField(_:shouldChangeCharactersIn:replacementString:) in a UIViewController:

import UIKitclass ViewController: UIViewController, UITextFieldDelegate {    @IBOutlet var textField: UITextField! // Link this to a UITextField in Storyboard    override func viewDidLoad() {        super.viewDidLoad()        textField.smartInsertDeleteType = UITextSmartInsertDeleteType.no        textField.delegate = self    }    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {        guard let textFieldText = textField.text,            let rangeOfTextToReplace = Range(range, in: textFieldText) else {                return false        }        let substringToReplace = textFieldText[rangeOfTextToReplace]        let count = textFieldText.count - substringToReplace.count + string.count        return count <= 10    }}


I do it like this:

func checkMaxLength(textField: UITextField!, maxLength: Int) {    if (countElements(textField.text!) > maxLength) {        textField.deleteBackward()    }}

The code works for me. But I work with storyboard. In Storyboard I add an action for the text field in the view controller on editing changed.


Update for Swift 4

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {     guard let text = textField.text else { return true }     let newLength = text.count + string.count - range.length     return newLength <= 10}