How to restrict certain characters in UITextField in Swift?

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

    Adding on to what @Evdzhan Mustafa said. You want to add a return statement in case the string is empty. Without it you won't be able to delete your text. Modified Code Below:

    Swift 3 Version

    let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.";
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.isEmpty{
            return true
        }
    
        print("String: \(string)")
        let set = NSCharacterSet(charactersIn: notAllowedCharacters);
        let inverted = set.inverted;
    
        let filtered = string.components(separatedBy: inverted).joined(separator: "")
        print("String Filtered: \(filtered)")
        return filtered != string;
    }
    

提交回复
热议问题