Skip to content

Instantly share code, notes, and snippets.

@adri567
Last active September 29, 2020 15:43
Show Gist options
  • Save adri567/ee1bea49cb3c28a9b027b368cd86a838 to your computer and use it in GitHub Desktop.
Save adri567/ee1bea49cb3c28a9b027b368cd86a838 to your computer and use it in GitHub Desktop.
NSTextField with only numbers and size limitation
extension MainViewController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
let textField = obj.object as! NSTextField
let charSet = NSCharacterSet(charactersIn: "1234567890").inverted
textField.onlyNumberAndTextFieldSizeLimitation(charset: charSet)
}
extension NSTextField {
func onlyNumberAndTextFieldSizeLimitation(charset: CharacterSet) {
let chars = stringValue.components(separatedBy: charset)
stringValue = chars.joined()
if stringValue.count > 8 {
stringValue = String(stringValue.dropLast())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment