How to restrict certain characters in UITextField in Swift?

前端 未结 8 2032
野的像风
野的像风 2020-12-06 19:44

I am creating a trivia application that asks for a username on start up. I\'d like to make it impossible to use characters such as #$@!^& etc (also including \"space\").

8条回答
  •  不知归路
    2020-12-06 20:42

    Swift 4 iOS 11.2.x based on using an extension, tests to see if a string is a valid hex number in this example.

    extension String {

    var containsValidCharacter: Bool {
        guard self != "" else { return true }
        let hexSet = CharacterSet(charactersIn: "1234567890ABCDEFabcdef")
        let newSet = CharacterSet(charactersIn: self)
        return hexSet.isSuperset(of: newSet)
      }
    }
    

    You use it like with the UITextFieldDelegate.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return (string.containsValidCharacter)
    }
    

提交回复
热议问题