带标识符的NSTableView单元格保持零 [英] NSTableView Cell with Identifier keep giving nil
问题描述
我正在构建MacOS应用程序.我试图使当我按下添加按钮时更新单元格的表视图.
I am working on building MacOS app. I am trying to make table view that updates the cell when I press add button.
以下是我的代码:
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let identifier = tableColumn?.identifier as NSString?
if ( identifier == "NameCell")
{
var result: NSTableCellView
let cell = tableView.make(withIdentifier: "NameCell", owner: self) as! NSTableCellView
cell.textField?.stringValue = self.data[row].setting!
return cell
}
else if (identifier == "SettingCell")
{
if let cell = tableView.make(withIdentifier: "SettingCell", owner: self) as? NSTableCellView {
cell.textField?.stringValue = self.data[row].setting!
return cell
}
}
return nil
}
但是,这一行让cell = tableView.make(withIdentifier:"NameCell",owner:self)为! NSTableCellView不断失败,因为它返回nil
However, the line let cell = tableView.make(withIdentifier: "NameCell", owner: self) as! NSTableCellView is keep failing because it returns nil
致命错误:解开可选值时意外发现nil
fatal error: unexpectedly found nil while unwrapping an Optional value
NameCell来自 谁能帮我找到解决这个问题的方法吗?
NameCell is from Can anyone please help me find a way to solve this problem?
推荐答案
对于尝试完全以编程方式制作NSTableView
时遇到相同问题的其他人:
For anyone else who comes here with this same question when trying to make an NSTableView
fully programmatically: makeView(withIdentifier:owner:)
WILL return nil
unless a corresponding NIB exists for the given identifier:
NSTableView
文档:
NSTableView
documentation:
如果无法从nib文件实例化或在重用队列中找到具有指定标识符的视图,则此方法返回nil
.
If a view with the specified identifier can’t be instantiated from the nib file or found in the reuse queue, this method returns nil
.
同样,所有者"参数是NIB特定的概念.简而言之:如果以编程方式用单元格填充NSTableView
,则不能使用此方法.
Likewise, the 'owner' param is a NIB-specific concept. In short: you cannot use this method if populating your NSTableView
with cells programmatically.
在此答案中,我详细介绍了Swift代码以编程方式生成NSTableCellView
: https://stackoverflow.com/a/51736468/5951226
In this answer, I detail the Swift code to produce an NSTableCellView
programmatically: https://stackoverflow.com/a/51736468/5951226
但是,如果您不希望NSTableViewCell
的所有功能,请注意,您可以在NSView
. com/documentation/appkit/nstableviewdelegate/1527449-tableview"rel =" noreferrer> tableView(_:viewFor:row:)
.因此,您可以按照 CocoaProgrammaticHowtoCollection ,只需写:
However, if you don't want all the features of an NSTableViewCell
, note that you can return any NSView
in tableView(_:viewFor:row:)
. So you could, as per the CocoaProgrammaticHowtoCollection, simply write:
let cell = NSTextField()
cell.identifier = "my_id" // Essential! Allows re-use of the instance.
// ... Set any properties you want on the NSTextField.
return cell
这篇关于带标识符的NSTableView单元格保持零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!