SWIFT: Nstextfield only accepts specified characters

I need someone to show me how to allow certain characters in nstexfield in swift. For example, when a user tries to enter a character that is not in the list, nstexfield will not show that character in the field. Very simple. There are many examples of iOS, but could not find an example of OSX.

+5
source share
2 answers

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: "") } 
+5
source

For Swift 3:

 override func controlTextDidChange(_ notification: Notification) { if textField == notification.object as? NSTextField { let characterSet: CharacterSet = (CharacterSet(charactersIn: "0123456789").inverted as NSCharacterSet) as CharacterSet textField.stringValue = (textField.stringValue.components(separatedBy: characterSet) as NSArray).componentsJoined(by: "") } } 
+1
source

Source: https://habr.com/ru/post/1242955/


All Articles