我对 NSTextField 进行了子类化,并为其分配了一个自定义 NumberFormatter。我使用 textDidChange() 方法读取文本字段的内容。一切都很顺利,除非输入“。” (作为小数分隔符)在文本字段中,整个文本消失。如果我不阅读文本,就不会发生这种情况。
我尝试重写一些从 NSControlTextEditingDelegate 继承的控制函数,但我还没有找到当我按“.”时有反应的函数。
Xcode 版本 10.3 (10G8)
swift 5
import Cocoa
class HRXNumbeField: NSTextField {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.formatter = HRXNumberFormatter()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func textDidChange(_ notification: Notification) {
print(self.stringValue) // comment this line to avoid text deletion
}
}
class HRXNumberFormatter: NumberFormatter {
override func isPartialStringValid(_ partialString: String,
newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?,
errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
if partialString.count == 0 { return true }
if let _ = Float(partialString) {
return true
}
else {
NSSound.beep()
return false
}
}
}
尝试注释 textDidChange() 中的行并查看差异。
最佳答案
问题在于,当您访问 textDidChange(_:)
内的 stringValue
以及自 以来,numberFormatter 会尝试验证文本字段的输入。
无法转换为 float ,拒绝 .
字符。
比设置自定义 NumberFormatter
并覆盖其 isPartialStringValid(_:newEditingString:errorDescription)
函数更简单的强制 Decimal 输入的方法是简单地覆盖 textDidChange
并删除其中的无效字符。
class HRXNumberField: NSTextField {
override func textDidChange(_ notification: Notification) {
let invalidChars = NSCharacterSet(charactersIn: "1234567890.").inverted
let validChars = stringValue.components(separatedBy: invalidChars)
stringValue = validChars.joined()
let separatedByDot = stringValue.components(separatedBy: ".")
if separatedByDot.count > 2 {
stringValue = separatedByDot[0] + "." + separatedByDot.dropFirst().joined()
}
print(self.stringValue)
}
}
关于swift - 按下期间意外删除 NSTextFiled 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57494937/