How to restrict certain characters in UITextField in Swift?

前端 未结 8 2027
野的像风
野的像风 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:31

    Swift : 3 and a different approach:

    Add a target function for the text field change in your viewDidLoad:

        override func viewDidLoad() {
        super.viewDidLoad()
    textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
     }
    

    in the target function, simply detect the entered char and replace it with blank. I have tested it and it prevents the user from entering any non desirable characters in the text field.

     func textFieldDidChange(textField: UITextField) {
    
        if let textInField = textField.text{
            if let lastChar = textInField.characters.last{
    
                //here include more characters which you don't want user to put in the text field
                if(lastChar == "*")
                {
    
                    textField.text  = textInField.substring(to: textInField.index(before: textInField.endIndex))
    
                }
            }
        }
    
    }
    

提交回复
热议问题