How to restrict certain characters in UITextField in Swift?

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

    Since you're explicitly asking for Swift, I've translated the top asnwer in the linked question.

    let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.";
    
    func textField(
        textField: UITextField,
        shouldChangeCharactersInRange range: NSRange,
        replacementString string: String)
        -> Bool
    {
        let set = NSCharacterSet(charactersInString: notAllowedCharacters);
        let inverted = set.invertedSet;
    
        let filtered = string
            .componentsSeparatedByCharactersInSet(inverted)
            .joinWithSeparator("");
        return filtered != string;
    
    }
    
    0 讨论(0)
  • 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))
    
                }
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-06 20:32

    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)
    }
    

    Although I read in an earlier post that CharacterSets do not support characters that are composed of more than one Unicode.Scalar; so use with caution I guess.

    0 讨论(0)
  • 2020-12-06 20:33
    internal func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
         if let text = string{
               if text == "#" || text == "$" || text == "!"{ \\and so on
                  return false
               }
         }
         return true
    }
    
    0 讨论(0)
  • 2020-12-06 20:35

    So this is probably the most robust way to restrict Spaces. Using this user won't be able to Paste/Type Whitespaces

    This is how you can Implement using Swift 3.

    Add below mentioned extension snippet to a Swift file;

    extension String {
    
    var containsWhitespace: Bool {
        for scalar in unicodeScalars {
            switch scalar.value {
            case 0x20:
                return true
            default:
                continue
            }
        }
        return false
      }
    }
    

    In your ViewController Swift file drag out your Editing Changed Instance and a Referencing Outlet of UITextField from Storyboard, the one mentioned in picture below:

    Use the dragged Instances as mentioned below:

    Referencing Outlet as:

    @IBOutlet weak var textField: UITextField!
    

    and Editing Changed as:

     @IBAction func textChanged(_ sender: UITextField) {
        if (textField.text!.containsWhitespace) == true {
            print("Restrict/Delete Whitespace")
            emailField.deleteBackward()
        } else {
            print("If Its not Whitespace, Its allowed.")
        }
    }
    

    This will detect and remove whitespace as soon as user tries to type/paste it.

    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
提交回复
热议问题