搜索后UITableView单元格索引异常,点击无法执行对应操作
问题分析
你遇到的核心问题是:搜索状态下,你把搜索结果列表的索引直接当成了原数组的索引。比如搜索到"Two",它在Filter数组里是第0项,但在原数组Array里是第1项,你用indexPath.row(此时是0)去匹配原数组的索引逻辑,自然会触发错误的分支。
解决方案
我们可以从两个方向修复这个问题,推荐第一种更稳妥的方式:
方案1:根据选中的文本内容执行逻辑(推荐)
直接获取当前选中单元格的文本,根据文本内容来判断要执行的操作,这样不管是原数组还是搜索结果,都能精准匹配:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedText: String if isSearching { selectedText = Filter[indexPath.row] } else { selectedText = Array[indexPath.row] } switch selectedText { case "One": print("one") case "Two": print("two") case "Three": print("three") case "Four": print("four") default: print("Error") } }
方案2:获取元素在原数组的真实索引
如果你必须依赖原数组的索引来执行逻辑,可以通过firstIndex(of:)找到搜索结果元素在原数组中的真实位置:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var realIndex: Int if isSearching { let selectedText = Filter[indexPath.row] // 找到该元素在原数组的真实索引 guard let index = Array.firstIndex(of: selectedText) else { print("Error: 元素不在原数组中") return } realIndex = index } else { realIndex = indexPath.row } switch realIndex { case 0: print("one") case 1: print("two") case 2: print("three") case 3: print("four") default: print("Error") } }
额外优化建议
- Swift命名规范里,变量名应该小写开头,比如
array、filterArray、tableView,这样代码可读性更好。 - 你的
cellForRowAt方法里有重复代码,可以简化:func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell // 三目运算符简化逻辑 cell.CellLabel.text = isSearching ? Filter[indexPath.row] : Array[indexPath.row] return cell }
内容的提问来源于stack exchange,提问作者Maxi
相关产品推荐
相关产品推荐

