【发布时间】:2017-08-11 16:41:56
【问题描述】:
我一直试图将 NSTableView 中的一个单元格更改为下拉菜单,但没有成功。我阅读了 Apple 开发人员文档,但没有给出如何在 NSTableView 中使用 NSPopupButtonCell 的示例。我搜索了论坛,包括这里,只找到了一个有点相关的例子,除了它是在 Objective-c 中,所以它不适用于我的 swift 应用程序。表格代码在这里:
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 添加到我的表格中时,我的表格单元格的所有视图都被删除了。所以我可能需要以不同的方式创建表。但是我读过并尝试过的大多数事情都导致了运行时错误或显示一个空表。
编辑: 第 3 天: 今天一直读到这里:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TableView/PopulatingViewTablesWithBindings/PopulatingView-TablesWithBindings.html 以及许多其他地方,但我没有代表发布更多链接。
我在 IB 中添加了一个 NSPopupButton,但不确定如何设置该值。我试过result.objectValue = homedevices[row].button,但这不起作用。我想我需要一个数组控制器对象。因此,我尝试在我的 DeviceListViewController 中为对象创建一个出口,例如 @IBOutlet var buttonArrayController: NSArrayController! 我想我现在需要以某种方式将阵列控制器连接到我的 homedevices 阵列。
所以我在这里查看了示例代码: https://github.com/blishen/TableViewPopup
这是在 Objective-C 中,这不是我正在使用的语言,但如果我在一周内的不同时间继续查看它,我可能会弄清楚如何制作下拉菜单。
所以我继续在这方面工作,目前没有解决方案。
【问题讨论】:
-
不要使用
NSPopupButtonCell。在基于视图的表视图中,只需将NSPopButton添加到该列的视图中。观看有关基于视图的表视图的 WWDC 2011 (!) 视频。 -
谢谢,我已经看了大约 30 分钟的视频。它有助于理解基于视图的表格,但演示代码都是 Objective-C。有 Swift 视频吗?
-
我确实注意到,如果我尝试为 NSPopUpButton 创建一个插座,构建失败并出现错误:插座无法连接到重复内容。
-
你必须继承
NSTableCellView来连接插座,我推荐视频来了解如何在单元格视图中处理自定义 UI 元素的原理,而不管语言如何。顺便说一句:ObjC -> Swift 翻译很容易。 -
vadian - 感谢您的帮助!我能够在子类中创建一个插座,现在下拉菜单就像他们应该做的那样工作!哇。那花了我很长时间。但我很高兴能学会如何做到这一点!
标签: swift macos nstableview