Cory Trentini
Cory Trentini

Reputation: 97

SWIFT: Nstextfield allow only specified characters

I need somebody to show me how to allow specific characters in a nstexfield in swift. For example when a user tries to enter a character which is not in the list the nstexfield will not show that character in the field.. Very simple. There are many IOS examples out there but could not find an OSX example.

Upvotes: 5

Views: 1387

Answers (3)

Xiaomu Gu
Xiaomu Gu

Reputation: 31

in swift 5.7:

If you just want to allow the input of numbers, then do this:

import Cocoa

class Main: NSViewController {

    @IBOutlet weak var textfield: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        textfield.delegate = self
    }
}
extension Main: NSTextFieldDelegate {
    func controlTextDidChange(_ obj: Notification) {
        let filtered = (obj.object as! NSTextField).stringValue.filter{"0123456789".contains($0)}
        if filtered != (obj.object as! NSTextField).stringValue {
            (obj.object as! NSTextField).stringValue = filtered
        }
    }
}

If you want to allow only specified characters to be entered, you can change the filter rules. like this:

let filtered = (obj.object as! NSTextField).stringValue.filter{"abcdefghijklmnopqrstuvwxyz".contains($0)}

Hope this helps you

Upvotes: 0

Koray Birand
Koray Birand

Reputation: 1986

First add a 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 have to replace self.textfield with your own textfield which 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: "")
}

Upvotes: 7

matanm
matanm

Reputation: 317

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

Upvotes: 2

Related Questions