我正在致力于构建 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
}
但是,行 let cell = tableView.make(withIdentifier: "NameCell",owner: self) as! NSTableCellView 一直失败,因为它返回 nil
致命错误:在解包可选值时意外发现 nil
NameCell is from
Can anyone please help me find a way to solve this problem?
对于任何其他在尝试制作时带着同样问题来到这里的人NSTableView
完全以编程方式:makeView(withIdentifier:owner:) https://developer.apple.com/documentation/appkit/nstableview/1535482-makeview将返回nil
除非给定标识符存在相应的 NIB:
NSTableView
文档:
如果具有指定标识符的视图无法从 nib 文件实例化或在重用队列中找到,则此方法返回nil
.
同样,“owner”参数是 NIB 特定的概念。简而言之:如果填充您的NSTableView
以编程方式使用单元格。
在这个答案中,我详细介绍了生成一个NSTableCellView
以编程方式:https://stackoverflow.com/a/51736468/5951226 https://stackoverflow.com/a/51736468/5951226
但是,如果您不想要一个的所有功能NSTableViewCell
,注意你可以返回any NSView
in tableView(_:viewFor:row:) https://developer.apple.com/documentation/appkit/nstableviewdelegate/1527449-tableview。所以你可以按照Cocoa 程序化 Howto 集合 https://github.com/eonil/CocoaProgrammaticHowtoCollection/blob/6dfad6c9f2fc059ce9cbe7dedbbea00304871fb2/ComponentUsages/NSTableViewExample/main.swift#L44,简单地写:
let cell = NSTextField()
cell.identifier = "my_id" // Essential! Allows re-use of the instance.
// ... Set any properties you want on the NSTextField.
return cell
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)