[英]How to Use NSTableViewDiffableDataSource to Load Data with NSTableView
[英]Accessing data in a struct for use in a NSTableView
我对编程很陌生,我已经坚持了一段时间。 我有一个名为 Patient 的结构,它充满了 var,例如 var FIRST: String。
我已经编写了从 JSON 检索数据并填充此结构的代码。 它工作正常,我可以调用 print(Patient) 并在控制台中看到所有数据。
该结构的实例是一个二维数组,所以当我打印到控制台时,我得到 Patient(FIRST: "Bob", LAST: "Smith") Patient(FIRST: "Dave", LAST: "Evans") Patient(FIRST: “丽兹”,最后一个:“泰勒”)
第一个 tableview 方法工作正常并返回 3 的计数。
第二个是我卡住的地方:
我声明:
static var globalPatientInstance: [Patient] = []
然后用来自完成处理程序的数据填充它。 这是第二种方法:
extension ViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let item = ViewController.globalPatientInstance[row]
let cell = tableView.makeView(withIdentifier: (tableColumn!.identifier), owner: self) as? NSTableCellView
cell?.textField?.stringValue = item[(tableColumn?.identifier)!]!
return cell!
}
}
这给出了“类型‘患者’没有下标成员”
但是,如果我将行更改为:
cell?.textField?.stringValue = item.FIRST
代码将运行,我在表视图中得到三行,每行都有不同的名称 - Bob、Dave、Liz。
获取其余数据的正确方法是什么,即 item.LAST 也显示?
感谢您的帮助,我尝试了很多不同的东西,但我真的坚持这一点。
“类型‘患者’没有下标成员” - 此错误是因为您试图将患者作为数组访问。 Item 是一个结构体,而不是一个数组。
当你说你的结构是一个二维数组时,这是没有意义的。 你的结构是一个结构。 您的“2D”数组只是结构的全局实例变量数组。 [患者] 是一维数组。
let item = ViewController.globalPatientInstance[row] // item is now a Patient struct
let cell = tableView.makeView(withIdentifier: (tableColumn!.identifier), owner: self) as? NSTableCellView
cell?.textField?.stringValue = item[(tableColumn?.identifier)!]! // This doesn't work because Patient is not an array, but a struct
cell?.textField?.stringValue = item.FIRST // This works because you are accessing the property of item
cell?.textField?.stringValue = item.LAST // This is to display the LAST property of item
return cell!
}
注意——请将您的类属性命名为驼峰式。您可以将此样式指南用作新手参考。
https://github.com/raywenderlich/swift-style-guide
此外 - 使用 first 和 last 是属性的错误命名约定,因为听起来first是数组的第一个元素。 我会推荐 firstName 和 lastName。
我想到了。 谢谢你们的帮助。 这个方法做我需要的:
extension ViewController: NSTableViewDelegate {
fileprivate enum CellIdentifiers {
static let firstName = "FIRST"
static let lastName = "LAST"
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var cellValue: String = ""
var cellIdentifier: String = ""
let item = ViewController.globalPatientInstance[row]
if tableColumn == tableView.tableColumns[0] {
cellValue = item.FIRST
cellIdentifier = CellIdentifiers.firstName
}
else if tableColumn == tableView.tableColumns[1] {
cellValue = item.LAST
cellIdentifier = CellIdentifiers.lastName
}
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView {
cell.textField?.stringValue = cellValue
//cell.textField?.stringValue = lastName
return cell
}
return nil
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.