首页 > 解决方案 > 搜索后我的表格视图单元格的索引发生了变化

问题描述

搜索单元格后,我想单击它并执行操作。但是搜索后,我的单元格的索引始终为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")
        }
    }
}

标签: iosswiftuitableview

解决方案


您需要将搜索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])
     }
 }

推荐阅读