0

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.

Andrew Tuzson
  • 619
  • 8
  • 28

2 Answers2

1

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
}
AshvinGudaliya
  • 3,234
  • 19
  • 37
  • The shouldChangeCharactersIn method did the trick. I updated my viewController class to include: let zipCodeDelegate = ZipCodeDelegate() As well as assigning the delegate within the viewDidLoad method like so: self.zipTextField.delegate = zipCodeDelegate I appreciate the help. Can you explain why your first solution works? I don't understand the syntax being used. – Andrew Tuzson Dec 08 '17 at 12:24
  • Must read this post [Implementing UITextFieldDelegate in a separate class](https://stackoverflow.com/a/28033112/6822622) – AshvinGudaliya Dec 08 '17 at 12:41
0

Swift 4

public class LimitedUITextField: UITextField, UITextFieldDelegate {
    var maxNumber: Int = 0 {
        didSet {
            self.delegate = self
        }
    }


    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textFieldText = self.text,
            let rangeOfTextToReplace = Range(range, in: textFieldText) else {
                return false
        }
        let substringToReplace = textFieldText[rangeOfTextToReplace]
        let count = textFieldText.count - substringToReplace.count + string.count
        return count <= self.maxNumber
    }
}
Thiha Aung
  • 11
  • 6