带标识符的NSTableView Cell保持为零

问题描述 投票:2回答:2

我正在构建MacOS应用程序。我正在尝试制作表格视图,当我按下添加按钮时更新单元格。

enter image description here

以下是我的代码:

 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

NameCell来自enter image description here任何人都可以帮我找到解决这个问题的方法吗?

macos cocoa swift3 nstableview nstableviewcell
2个回答
3
投票

您应该在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
}

XCode Interface Builder中的引用设置:enter image description here


2
投票

对于在尝试以编程方式完成NSTableView时遇到同样问题的其他任何人:makeView(withIdentifier:owner:)将返回nil,除非给定标识符存在相应的NIB:

NSTableView文件:

如果无法从nib文件实例化具有指定标识符的视图或在重用队列中找到该视图,则此方法将返回nil

同样,“所有者”参数是特定于NIB的概念。简而言之:如果以编程方式使用单元格填充NSTableView,则无法使用此方法。

在这个答案中,我详细介绍了Swift代码以编程方式生成NSTableCellViewhttps://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
© www.soinside.com 2019 - 2024. All rights reserved.