How can I declare that a text field can only contain an integer?

前端 未结 9 1919
星月不相逢
星月不相逢 2020-11-30 05:37

In swift, I am trying to make a text field that will allow a button to be enabled, but only when the text field contains an integer. How can I do this?

9条回答
  •  孤街浪徒
    2020-11-30 06:31

    Swift 4: How about a simple guard and typecasting to Int as below

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
            guard let _ = Int(string) else {
                button.isEnabled = false
                return true
            }
                button.isEnabled = true
                return true
    }
    

提交回复
热议问题