使用 swift 使用 NSPopupButtonCell 填充 NSTableView 行

Using swift to populate NSTableView rows with a NSPopupButtonCell

我一直在尝试将 NSTableView 中的一个单元格更改为下拉菜单,但没有成功。我阅读了 Apple 开发人员文档,但它没有给出如何在 NSTableView 中使用 NSPopupButtonCell 的示例。我搜索了论坛,包括这里,只找到了一个有点相关的例子,除了它在 objective-c 中,所以它不适用于我的 swift 应用程序。 table 的代码在这里:

extension DeviceListViewController:NSTableViewDataSource, NSTableViewDelegate{
// get the number of rows for the table
func numberOfRows(in tableView: NSTableView) -> Int {
   return homedevices.count
}
// use the data in the homedevices array to populate the table cells
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?{
    let result  = tableView.make(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView
    if tableColumn?.identifier == "ID" {
        result.textField?.stringValue = homedevices[row].id
    } else if tableColumn?.identifier == "Name" {
        result.textField?.stringValue = homedevices[row].name
        result.imageView?.image = homedevices[row].image
    } else if tableColumn?.identifier == "Type" {
        result.textField?.stringValue = homedevices[row].type
    } else if tableColumn?.identifier == "Button" {
        result.textField?.integerValue = homedevices[row].button
    }
    return result
}
// facilitates data sorting for the table columns
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
    let dataArrayMutable = NSMutableArray(array: homedevices)
    dataArrayMutable.sort(using: tableView.sortDescriptors)
    homedevices = dataArrayMutable as! [HomeDevice]
    tableView.reloadData()
}


}

我真的只是希望能够允许下拉选择来更改分配给特定家庭设备的按钮(一个简单的整数),而不必在文本字段中键入数字来编辑此值。不幸的是,当我在 IB 中将 popupbuttoncell 添加到我的 table 时,我的 table 单元格的所有视图都被删除了。所以我可能需要以不同的方式创建 table 。但是我阅读和尝试过的大部分内容都导致运行时错误或显示空 table。

编辑: 第 3 天: 今天我一直在这里阅读:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TableView/PopulatingViewTablesWithBindings/PopulatingView-TablesWithBindings.html 还有许多其他地方,但我没有代表 post 任何更多链接。

我在 IB 中添加了一个 NSPopupButton,但我不确定如何设置该值。我试过 result.objectValue = homedevices[row].button,但那不起作用。我想我需要一个数组控制器对象。因此,我尝试在我的 DeviceListViewController 中为对象创建一个出口,例如 @IBOutlet var buttonArrayController: NSArrayController! 我想我现在需要以某种方式找到一种方法将阵列控制器连接到我的 homedevices 阵列。

所以我在这里查看了示例代码: https://github.com/blishen/TableViewPopup

这是在 objective-C 中,这不是我正在使用的语言,但也许如果我在一周的不同时间不断查看它,我可能会想出如何拉动-向下菜单。

所以我正在继续努力,目前没有解决方案。

这个问题已经解决了,感谢@vadian。
该按钮作为 NSPopUpButton 对象插入,而不是 NSPopUpButtonCell。 然后单元格获得自己的自定义 class,我将其称为 ButtonCellView 作为 NSTableCellView.
的子class 然后创建的 subclass 可以接收从 NSPopUpButton 到自定义 subclass 的出口。我可以给它一个 selectedItem 变量并在此处创建菜单。 然后在 table 视图委托中,当创建 table 时,我可以将 ButtonCellView 对象的 selectedItem 设置为数据数组中的值。 效果很好!