这是我的解决方案。认为搜索文本字段位于索引 0 中。您需要更新或添加或删除下一行。
let beforeCount = self.filteredItems.count
self.filteredItem = ... next filtered items
var removalIndexPaths = [IndexPath]()
var appendalIndexPaths = [IndexPath](
var modifyIndexPaths = [IndexPath]()
self.tableView.beginUpdates()
let deleteAvailable = beforeCount != 0
if deleteAvailable {
for i in stride(from: beforeCount - 1, to: 0, by: -1) {
removalIndexPaths.append(IndexPath(row: i, section: 0))
}
}
let appendAvailable = self.filteredShots.count != 0
if appendAvailable {
for i in stride(from: 1, to: self.filteredShots.count, by: 1) {
appendalIndexPaths.append(IndexPath(row: i, section: 0))
}
}
modifyIndexPaths = appendalIndexPaths.filter { appendPath in
if appendPath == removalIndexPaths.filter({ $0 == appendPath }).first {
return true
} else {
return false
}
}
for item in modifyIndexPaths {
if let rai = appendalIndexPaths.firstIndex(where: { $0 == item}) {
appendalIndexPaths.remove(at: rai)
}
if let rri = removalIndexPaths.firstIndex(where: { $0 == item}) {
removalIndexPaths.remove(at: rri)
}
}
if modifyIndexPaths.count > 0 {
self.tableView.reloadRows(at: modifyIndexPaths, with: .none)
}
if removalIndexPaths.count > 0 {
self.tableView.deleteRows(at: removalIndexPaths, with: .none)
}
if appendalIndexPaths.count > 0 {
self.tableView.insertRows(at: appendalIndexPaths, with: .none)
}
self.tableView.endUpdates()