Search code examples
swiftxcodedelegatesuitextfielduitextfielddelegate

Create UITextFieldDelegate to Limit Character Count in Swift


I am new to delegates and I am trying to experiment with the UITextFieldDelegate. My goal is to limit the character count within this text field to five characters, as if I were creating a zip code text field.

I am using an off the shelf view controller with a text field and I created a delegate file titled ZipCodeDelegate.swift. I have modified the text field in the storyboard to display the number keypad when the user taps the field. Here is my viewController:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

// MARK: Outlets

@IBOutlet weak var zipTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

And here is my delegate file:

import Foundation
import UIKit

class ZipCodeDelegate: NSObject, UITextFieldDelegate {


}

I am at a loss for what to do next. I am unsure how to limit the character count of the textfield, as well as telling the view controller that this delegate file exists and that it should control said text field.


Solution

  • Use this UITextField delegate for Zipcode and Int Limit Character count

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        if string.rangeOfCharacter(from: NSCharacterSet.decimalDigits.inverted) == nil{
            let len = (textField.text?.characters.count)! + string.characters.count
            if len <= 5 {
                return true
            }
        }
        return false
    }
    

    UITextField delegate method for check the max character limit.

    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        var oldlength : Int = 0
        if textField.text != nil
        {
            oldlength = (textField.text?.count)!
        }
    
        let replaceMentLength : Int = string.count
        let rangeLength : Int = range.length
    
        let newLength : Int = oldlength - rangeLength + replaceMentLength
    
        return newLength <= charaterLimit || false
    }