Allow only alphanumeric characters for a UITextField

前端 未结 7 924
野性不改
野性不改 2020-11-27 17:44

How would I go about allowing inputting only alphanumeric characters in an iOS UITextField?

相关标签:
7条回答
  • 2020-11-27 18:23

    The RegEx way in Swift:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         if string.isEmpty {
             return true
         }
         let alphaNumericRegEx = "[a-zA-Z0-9]"
         let predicate = NSPredicate(format:"SELF MATCHES %@", alphaNumericRegEx)
         return predicate.evaluate(with: string)
    }
    
    0 讨论(0)
提交回复
热议问题