簡體   English   中英

如何使用 NSTableViewDiffableDataSource 通過 NSTableView 加載數據

[英]How to Use NSTableViewDiffableDataSource to Load Data with NSTableView

我正在嘗試學習如何使用NSTableViewDiffableDataSource通過NSTableView加載數據。 我可以使用UITableViewDiffableDataSourceUICollectionViewDiffableDataSource在 iOS 中加載數據,因為我在網上找到了一些示例。 但我無法在 Cocoa 中使用NSTableViewDiffableDataSource

在下面的例子中,我有一個名為TestTableCellViewNSTableCellView子類,它顯示了三個字段:名字、姓氏和他或她的出生日期(以字符串表示)。

import Cocoa

class ViewController: NSViewController {
    // MARK: - Variables
    var dataSource: NSTableViewDiffableDataSource<Int, Contact>?
    
    
    // MARK: - IBOutlet
    @IBOutlet weak var tableView: NSTableView!
    
    
    // MARK: - Life cycle
    override func viewWillAppear() {
        super.viewWillAppear()
        
        let model1 = Contact(id: 1, firstName: "Christopher", lastName: "Wilson", dateOfBirth: "06-02-2001")
        let model2 = Contact(id: 2, firstName: "Jen", lastName: "Psaki", dateOfBirth: "08-25-1995")
        let model3 = Contact(id: 3, firstName: "Pete", lastName: "Marovich", dateOfBirth: "12-12-2012")
        let model4 = Contact(id: 4, firstName: "Deborah", lastName: "Mynatt", dateOfBirth: "11-08-1999")
        let model5 = Contact(id: 5, firstName: "Christof", lastName: "Kreb", dateOfBirth: "01-01-2001")
        let models =  [model1, model2, model3, model4, model5]
        
        dataSource = NSTableViewDiffableDataSource(tableView: tableView, cellProvider: { tableView, tableColumn, row, identifier in
            let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: self) as! TestTableCellView
            let model = models[row]
            cell.firstField.stringValue = model.firstName
            cell.lastField.stringValue = model.lastName
            cell.dobField.stringValue = model.dateOfBirth
            return cell
        })
        tableView.dataSource = dataSource
        guard let dataSource = self.dataSource else {
            return
        }
        var snapshot = dataSource.snapshot()
        snapshot.appendSections([0])
        snapshot.appendItems(models, toSection: 0)
        dataSource.apply(snapshot, animatingDifferences: true, completion: nil) // <--- crashing...
    }
}

struct Contact: Hashable {
    var id: Int
    var firstName: String
    var lastName: String
    var dateOfBirth: String
}

嗯......應用程序崩潰並出現錯誤“無效參數不令人滿意:快照。 ”幾天前,我測試了另一個示例,它也在同一行(dataSource.apply)崩潰。 我在網上找不到很多涉及NSTableViewDiffableDataSource的示例。 我發現的唯一例子是他的主題,這沒有幫助。 無論如何,我做錯了什么? 我的 Xcode 版本是 13.1。 謝謝。

創建這樣的快照,它應該可以工作:

guard let dataSource = self.dataSource else {
    return
}

var snapshot = NSDiffableDataSourceSnapshot<Int, Contact>()
snapshot.appendSections([0])
snapshot.appendItems(models, toSection: 0)
dataSource.apply(snapshot, animatingDifferences: false)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM