Ask Your Question

Revision history [back]

One approach to ensure that a UITextField only accepts integers and a maximum of 10 digits in Swift 5 is to use the UITextFieldDelegate and implement the shouldChangeCharactersIn method.

Here's an example implementation:

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var numberTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // set delegate to self
        numberTextField.delegate = self
    }

    // UITextFieldDelegate method to limit input to integers and max 10 characters
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        // get the new string after adding the replacement string
        let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)

        // output the new string for debugging purposes
        print("new string: \(newString)")

        // check if the new string is a valid integer and has max 10 digits
        if let _ = Int(newString), newString.count <= 10 {
            return true
        } else {
            return false
        }
    }
}

In this implementation, we set the view controller as the delegate for the numberTextField and implement the UITextFieldDelegate method shouldChangeCharactersIn.

Inside this method, we first get the new string by replacing the string in the specified range with the replacement string. We then check if this new string is a valid integer and has a maximum of 10 digits. If it meets these criteria, we allow the change to be made, otherwise we block it.

Note that we also included a print statement to output the new string for debugging purposes. You can remove this line in your implementation.

Using this implementation, the UITextField will only allow integers and a maximum of 10 digits to be inputted.