【问题标题】:How to reload NSTableView data when NSSearchField text changesNSSearchField 文本更改时如何重新加载 NSTableView 数据
【发布时间】:2022-03-19 02:35:23
【问题描述】:

我对如何在 searchField 的文本更改时重新加载 NSTableView 的数据感到有些困惑。我假设我需要根据字符串匹配和tableView.reloadData() 内部的所有controlTextDidChange() 调用过滤tableView 用来填充自身的数组,但是当我测试代码时它不起作用。我假设这将是一个非常简单的修复,并且我在这个主题上找到的大部分信息都有些复杂。所以我不知道解决方案到底有多简单或复杂

这是我的controlTextDidChange() 函数:

func controlTextDidChange(_ obj: Notification) {
    noteRecords.filter { $0.title.contains(searchField.stringValue) }
    tableView.reloadData()
}

如果有人可以解释如何在 searchField 的文本更改时使用过滤后的数组重新加载 tableViews 数据,那将非常感激。另外,如果用普通的 NSTextField 替换 searchField 更容易,请告诉我。

编辑

这是填充 tableView 的函数:

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    let note = allRecords[row]
    let cellIdentifier = NSUserInterfaceItemIdentifier(rawValue: \"NoteInCloudCell\")
    
    if tableColumn == tableView.tableColumns[0] {
        let cell = tableView.makeView(withIdentifier: cellIdentifier, owner: nil) as? NoteInCloudCell
        cell?.noteTitle.stringValue = note.title
        cell?.cloudID.stringValue = note.cloudID
        return cell
    }
    else { return nil }
}

    标签: swift nstableview nstextfield nssearchfield


    【解决方案1】:

    创建与noteRecords 相同类型的第二个数组并将其命名为allRecords

    将完整的记录集分配给allRecords,并使用noteRecords作为数据源数组

    controlTextDidChange 替换为

    func controlTextDidChange(_ obj: Notification) {
        let query = searchField.stringValue
        if query.isEmpty {
            noteRecords = allRecords
        } else {
            noteRecords = allRecords.filter { $0.title.localizedCaseInsensitiveContains(query)
        }
        tableView.reloadData()
    }
    

    一种更复杂的方法是 diffable 数据源。

    【讨论】:

    • 我对使用noteRecords 作为数据源数组的意思有点困惑,您能否提供有关该部分的更多详细信息?我已经编辑了问题以显示填充表格的 tableView 函数。
    • 我的建议需要两个相同类型的数组。数组 #1 包含所有项目并且永远不会被修改。数组 #2 在 numberOfRowsviewFor:row: 中用作数据源数组,并在开始时和搜索时填充某处。在您的代码中,allRecords 是数据源数组,因此请使用另一个数组来保存所有项目。
    • 非常感谢,我遇到了麻烦,因为我将 note Records = all Records 设置在错误的位置。一旦我将它设置在我查询它工作的所有记录的任务块内
    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    相关资源
    最近更新 更多