Bossvanlindt
Bossvanlindt

Reputation: 51

Blocking some of number pad's numbers so that it is adapted to the user input.

My app asks the user for a precise number of minutes which she/he inserts using a number pad keyboard. I'd like to block the keyboard's numbers >5 for the first number the user types (so that they can't type a number of minutes > 59). For the second number, I'd like it to unblock the previously blocked numbers so that the minutes can be precisely inserted (e.g. 18 or 59). Is there a way to do this? If so, how?

Upvotes: 1

Views: 81

Answers (1)

Julien Quere
Julien Quere

Reputation: 2459

You should work with textField(_:shouldChangeCharactersIn:replacementString:) from the UITextFieldDelegate.

Here is a working example of what you can do:

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        var startString =  NSString()
        if textField.text != nil {
            startString = textField.text! as NSString
        }

        let endString = startString.stringByReplacingCharactersInRange(range, withString: string)

         if endString.isEmpty == true {
            return true
         }


        let intValue = Int(endString)
        if intValue >= 0 && intValue < 60 {
            return true
        }

        return false
    }

In this case, it will allow every integer value between 0 (included) and 60 (excluded).

Edit: This method is called by the UITextField on it's delegate (if you don't understand what is a delegate, take some time to read this and this, this pattern is very important).

So, to make the method above works, you just have to say to your UITextField that your UIViewController is its delegate. You can do it in the code (in viewDidLoad for example) or in Interface Builder. Here is a fully working example:

class MyViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        var startString = NSString()
        if textField.text != nil {
            startString = textField.text! as NSString
        }

        let endString = startString.stringByReplacingCharactersInRange(range, withString: string)

         if endString.isEmpty == true {
            return true
         }    

        let intValue = Int(endString)
        if intValue >= 0 && intValue < 60 {
            return true
        }

        return false
    }
}

Upvotes: 1

Related Questions