![](/img/trans.png)
[英]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.