Limit UITextField input to numbers in Swift

后端 未结 6 1119
南旧
南旧 2020-12-05 12:10

How can I get limit the user\'s TextField input to numbers in Swift?

6条回答
  •  情深已故
    2020-12-05 12:57

    For anyone looking for a shorter answer, I've found this quite useful.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // remove non-numerics and compare with original string
        return string == string.filter("0123456789".contains)
    }
    

    Works in XCode 10.1, Swift 4.2

提交回复
热议问题