【发布时间】:2019-03-24 13:07:00
【问题描述】:
我为我的特定用途对 NumberFormatter 进行了子类化,当我从代码中调用它时它工作得很好。这是子类:
class MyNumberFormatterUnitPrice: NumberFormatter {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init() {
super.init()
setup()
}
private func setup() {
self.format = "#,##0.00####;(#,##0.00####)"
self.numberStyle = .currencyAccounting
}
}
我这样做是因为,虽然可以在情节提要中设置正负格式,但您不能设置这些格式和“currencyAccounting”。但是,当我在情节提要中创建 NumberFormatter 时,选择此子类,然后将其放在我要格式化的列的文本单元格下,它似乎在以下范围内被覆盖:
tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?
在这里,我目前正在按此逻辑设置单元格:
let cellIdentifier = tableColumn!.identifier.rawValue
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(cellIdentifier), owner: nil) as? NSTableCellView {
...
我相信我是通过它的标识符从 tableview 中获取 tableviewcell 而不是创建一个新的,所以它应该有它的文本字段。我阅读了文档,这似乎是正确的方法。如果我在此处获取单元格后设置了 numberformatter,则它可以工作。但我不想这样做,因为我不想要一个巨大的 case 语句来设置特定的单元格属性——我想在故事板编辑器中这样做。
关于如何使用故事板编辑器设置数字格式化器的任何建议?
编辑:除此之外,我在设置文本字段的字符串值的位置放置了一个断点,并且文本设置如下:
textfield.stringValue = text
查看数字格式化程序在调试器中的位置,它设置在表列级别 - 这似乎不正确。但它肯定还在那里,而且还没有以某种方式被改写。
(lldb) e ((tableColumn?.dataCell as! NSTextFieldCell).formatter as! NumberFormatter).format
(String) $R14 = "#,##0.00####;0.00;(#,##0.00####)"
而且文本字段的格式化程序是 nil... 很奇怪。
(lldb) e textfield.formatter
(Formatter?) $R26 = nil
我要回去检查情节提要,看看我是否将格式化程序放在错误的地方。
【问题讨论】:
-
为该列子类化 NSTableViewCell 并在那里使用您的格式化程序。 (你可能不需要子类 NumberFormatter,只需要表格单元类)你可以在 IB 中引用表格单元子类。
-
.currencyAccounting只是一种预定义的数字格式样式。在 IB 中,将格式化程序设置为 OS X 10.4+ Default 和 Style Currency Accounting。切换到 OS X 10.4+ Custom 并自定义格式。 -
@Ron,我现在正在考虑对 NSTableViewCell 进行子类化。
-
@Willeke,我已经自定义了格式,但正如我上面所说,它在我的代码中以某种方式被覆盖,即使我不知道如何。我不会在任何地方创建新的文本单元格。
-
问题是“如何使用storyboard editor设置numberformatter?”还是您想使用
NumberFormatter的子类?
标签: swift xcode interface-builder nstableview nsnumberformatter