How to restrict UITextField to take only numbers in Swift?

后端 未结 30 939
难免孤独
难免孤独 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条回答
  •  旧时难觅i
    2020-12-04 09:14

    I think you can force change the keyboard type by implementing UITextInputTraits protocol, optional var keyboardType

    //class ViewController: UIViewController, UITextInputTraits {
    
    @IBOutlet weak var textFieldKeyboardType: UITextField!{
        didSet{
            textFieldKeyboardType.keyboardType = UIKeyboardType.NumberPad
        }
    }
    var keyboardType: UIKeyboardType { 
        get{ 
            return textFieldKeyboardType.keyboardType
        } 
        set{ 
            if newValue != UIKeyboardType.NumberPad{
                self.keyboardType = UIKeyboardType.NumberPad
            }
        } 
    }
    

提交回复
热议问题