How to restrict UITextField to take only numbers in Swift?

后端 未结 30 896
难免孤独
难免孤独 2020-12-04 08:40

I want the user to only enter numeric values in a UITextField. On iPhone we can show the numeric keyboard, but on iPad the user can switch to any keyboard.

30条回答
  •  抹茶落季
    2020-12-04 09:15

    Here is a simple solution, you need to connect the event "Editing changed" to this method in your controller

    Swift 4

    @IBAction func valueChanged(_ sender: UITextField) {
        if let last = sender.text?.last {
            let zero: Character = "0"
            let num: Int = Int(UnicodeScalar(String(last))!.value - UnicodeScalar(String(zero))!.value)
            if (num < 0 || num > 9) {
                //remove the last character as it is invalid
                sender.text?.removeLast()
            }
        }
    }
    

提交回复
热议问题