使用UISearchController搜索后编辑已过滤数组的最佳方法

问题描述 投票:0回答:1

我目前有一个带有Memories数组的UITableViewController(这是一个带有两个变量的结构 - memoryTitle和memoryDe​​scription)。在didSelectRowAt中,我让它运行以下功能以允许用户编辑项目。

func configure(memory: Memory, position: Int) {
    guard let vc = storyboard?.instantiateViewController(withIdentifier: "AddMemoryViewController") as? AddMemoryViewController else {
        fatalError("Unable to create AddMemoryViewController")
    }

selectedMemory = position
vc.delegate = self
vc.memory = memory
navigationController?.pushViewController(vc, animated: true)

}

一旦完成编辑,我的AddMemoryViewController将数据发送回它的委托(这是我的原始表视图)并使用以下代码更新内存:

  func update(memory: Memory) {
        guard let selectedMemory = selectedMemory else { return }

        memories[selectedMemory] = memory
        saveData()
        tableView.reloadData()
    }

这一直很好,但现在我正在尝试在原始表视图上实现UISearchController。我正在尝试使用的当前方法是使用filteredMemories数组。如果我使用filteredMemories并尝试编辑其中一个项目,我不知道如何再次更新原始项目(因为每个数组之间项目的索引不同)。我认为答案就在于将Memories改为一个类(所以过滤的记忆和记忆正在编辑同一个对象),但如果有人可以提供一些如何解决这个问题的指导,那就好了吗?

提前谢谢了!

ios swift class struct uisearchcontroller
1个回答
0
投票

要使用IndexSet,您可以执行以下操作。鉴于以下数据:

var dataArray = ["A1", "B1", "A2", "C1", "C2", "A3"]
//                0     1     2     3     4     5

// filter for "A*", here hard coded, in real live you would
// calculate it dynamically:
var index : IndexSet = [0,2,5] // Index of "A*" in dataArray

// Example: get data for row == 2
var dataIndex = index[2] // 5
var data = dataArray[dataIndex] // "A3"

所以:

  • 过滤时,将原始数组的匹配索引存储到IndexSet
  • numberOfRows将返回索引集的计数
  • cellForRow将从索引集中检索原始索引,从原始数组中获取相应的条目,并配置单元格 所以对于row==2,得到dataArray[index[2]]
  • 更新将执行相同的操作:获取索引,然后获取数据
© www.soinside.com 2019 - 2024. All rights reserved.