我需要有人向我展示如何在swift中允许nstexfield中的特定字符。例如,当用户尝试输入不在列表中的字符时,nstexfield将不会在字段中显示该字符。非常简单。有许多IOS示例,但找不到OSX示例。
答案 0 :(得分:7)
首先将NSTextFieldDelegate添加到您的类......然后
添加:
override func controlTextDidChange(obj: NSNotification) {
let characterSet: NSCharacterSet = NSCharacterSet(charactersInString: " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-_").invertedSet
self.textField.stringValue = (self.textField.stringValue.componentsSeparatedByCharactersInSet(characterSet) as NSArray).componentsJoinedByString("")
}
您必须将self.textfield替换为您想要控制的文本字段。
SWIFT 4编辑
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: "")
}
答案 1 :(得分:1)
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: "")
}
}