mrmabx mrmabx - 4 months ago 10
iOS Question

Remove all non a-zA-Z and non number strings form textfield

The user should be enter only a-z, A-Z and 0-9. I show the user the UIKeyboardType.ASCIICapable keyboard layout.

How can i filter non a-z, A-Z and 0-9 from string after the user enter a string with keyboard.

How can i solve this issue? I'm using xcode 7 and swift 2.

Answer

You need to work with delegate method of UITextField

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let set: NSCharacterSet = NSCharacterSet.alphanumericCharacterSet().invertedSet

       if string.rangeOfCharacterFromSet(set) != nil {
        return false
        }
        return true
    }
Comments