我正在构建MacOS应用程序。我正在尝试制作表格视图,当我按下添加按钮时更新单元格。
以下是我的代码:
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
致命错误:在展开Optional值时意外发现nil
您应该在NSTableCellView中使用“NameCell”设置“Identifier”。您的代码应简化如下,因为列的标识符永远不会更改:
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var result: NSTableCellView
let cell = tableView.make(withIdentifier: "NameCell", owner: self) as! NSTableCellView
cell.textField?.stringValue = self.data[row].setting!
return cell
}
对于在尝试以编程方式完成NSTableView
时遇到同样问题的其他任何人:makeView(withIdentifier:owner:)
将返回nil
,除非给定标识符存在相应的NIB:
NSTableView
文件:如果无法从nib文件实例化具有指定标识符的视图或在重用队列中找到该视图,则此方法将返回
nil
。
同样,“所有者”参数是特定于NIB的概念。简而言之:如果以编程方式使用单元格填充NSTableView
,则无法使用此方法。
在这个答案中,我详细介绍了Swift代码以编程方式生成NSTableCellView
:https://stackoverflow.com/a/51736468/5951226
但是,如果您不想要NSTableViewCell
的所有功能,请注意您可以在NSView
中返回任何tableView(_:viewFor:row:)
。所以你可以,根据CocoaProgrammaticHowtoCollection,只需写:
let cell = NSTextField()
cell.identifier = "my_id" // Essential! Allows re-use of the instance.
// ... Set any properties you want on the NSTextField.
return cell