ios - 搜索后我的表格视图单元格的索引发生了变化
问题描述
搜索单元格后,我想单击它并执行操作。但是搜索后,我的单元格的索引始终为0,因为它是表格视图中的第一件事。
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var TableView: UITableView!
@IBOutlet weak var SearchBar: UISearchBar!
var Array = ["One","Two","Three","Four"]
var myIndex = Int()
var Filter = [String]()
var isSearching = false
override func viewDidLoad() {
super.viewDidLoad()
TableView.delegate = self
TableView.dataSource = self
SearchBar.delegate = self
SearchBar.returnKeyType = UIReturnKeyType.done
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching {
return Filter.count
}
return Array.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = TableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell
cell.CellLabel.text = Array[indexPath.row]
if isSearching {
cell.CellLabel.text = Filter[indexPath.row]
}else {
cell.CellLabel.text = Array[indexPath.row]
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if SearchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
TableView.reloadData()
}else {
isSearching = true
Filter = Array.filter({$0.contains(searchBar.text!)})
TableView.reloadData()
}}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
switch myIndex {
case 0:
print("one")
case 1:
print("two")
case 2:
print("three")
case 3:
print("four")
default:
print("Error")
}
}
}
解决方案
您需要将搜索isSearching
逻辑放入其中didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var index = 0
if isSearching {
index = Array.index(of:Filter[indexPath.row])
}
else {
index = Array.index(of:Array[indexPath.row])
}
}
推荐阅读
- facebook-messenger-bot - Facebook Messenger Bot - 将控制权从机器人传递给人类并启用键盘输入
- python - Flask 和 Certbot
- java - 二叉搜索树搜索疑难解答
- java - NetBeans 电子商务教程提交订单错误
- f# - 在 .NET 核心上使用 F# 时删除编译器警告
- html - 放置叠加层后框阴影不起作用
- c# - 在 C# 中打印模式
- php - 无法使用 find 和 exec 移动?
- android - 当 SMS 到达 Android oreo 时,如何使用广播接收器获得警报/通知?
- django - 如何访问字典键作为 django 模板中列表索引的索引