SWIFT: Nstextfield 只允许指定的字符
SWIFT: Nstextfield allow only specified characters
我需要有人告诉我如何在 swift 的 nstexfield 中允许特定字符。例如,当用户尝试输入不在列表中的字符时,nstexfield 将不会在字段中显示该字符。非常简单。那里有很多 IOS 个示例,但找不到 OSX 个示例。
首先将 NSTextFieldDelegate 添加到您的 class... 然后
添加这个:
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: "")
}
对于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: "")
}
}
我需要有人告诉我如何在 swift 的 nstexfield 中允许特定字符。例如,当用户尝试输入不在列表中的字符时,nstexfield 将不会在字段中显示该字符。非常简单。那里有很多 IOS 个示例,但找不到 OSX 个示例。
首先将 NSTextFieldDelegate 添加到您的 class... 然后
添加这个:
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: "")
}
对于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: "")
}
}