Ask Your Question
1

What steps can be taken in Swift 5 to ensure that UITextField only accepts integers and a maximum of 10 digits?

asked 2021-06-20 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-02 14:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-20 11:00:00 +0000

Seen: 9 times

Last updated: Dec 02 '21