我终于通过完全删除格式化程序并仅将字符串过滤到controlTextDidChange
. 请注意,这适用于NSTextField
和NSSearchField
。
class ViewController: NSViewController {
@IBOutlet var searchField: NSSearchField! // delegate is set in SB
lazy var decimalCharacterSet: CharacterSet = {
var charSet = CharacterSet.init(charactersIn: "0123456789")
charSet.insert(charactersIn: Locale.current.decimalSeparator!)
return charSet
}()
}
extension ViewController: NSControlTextEditingDelegate {
func controlTextDidChange(_ notification: Notification) {
if let textField = notification.object as? NSTextField {
// first filter out all the non-numbers
let chars = textField.stringValue.components(separatedBy: decimalCharacterSet.inverted)
var result = chars.joined()
// now check if there are more than one decimal separators
let count = result.filter { $0 == Character(Locale.current.decimalSeparator!) }.count
// if so, remove the last character in the string, this is what has just been typed.
if count > 1 {
result = String(result.dropLast())
}
// finally, assign the filtered string back to the textField
textField.stringValue = result
}
}
}