First add NSTextFieldDelegate to your class ... and then
add this:
override func controlTextDidChange(obj: NSNotification) { let characterSet: NSCharacterSet = NSCharacterSet(charactersInString: " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-_").invertedSet self.textField.stringValue = (self.textField.stringValue.componentsSeparatedByCharactersInSet(characterSet) as NSArray).componentsJoinedByString("") }
you need to replace self.textfield with your own text field that you want to control.
SWIFT 4 Edit
override func controlTextDidChange(_ obj: Notification) { let characterSet: NSCharacterSet = NSCharacterSet(charactersIn: " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-_").inverted as NSCharacterSet self.textField.stringValue = (self.textField.stringValue.components(separatedBy: characterSet as CharacterSet) as NSArray).componentsJoined(by: "") }
source share