Although itβs too late to answer, this answer may be useful to someone.
It is simple and works like a charm to me.
Swift 3:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { /// 1. replacementString is NOT empty means we are entering text or pasting text: perform the logic /// 2. replacementString is empty means we are deleting text: return true if string.characters.count > 0 { var allowedCharacters = CharacterSet.alphanumerics /// add characters which we need to be allowed allowedCharacters.insert(charactersIn: " -") // "white space & hyphen" let unwantedStr = string.trimmingCharacters(in: allowedCharacters) return unwantedStr.characters.count == 0 } return true }
Note. This will work for inserting lines into a text field. The inserted line will not be displayed in the text box if it contains any unwanted characters.
Rishi source share