Индекс моих ячеек таблицы изменяется после поиска - PullRequest
0 голосов
/ 23 мая 2018

После поиска ячейки я хотел бы щелкнуть по ней и выполнить действие.Но после поиска индекс моей ячейки всегда равен 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")
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 23 мая 2018

Внутри вашего метода tableView (: didSelectRowAt) вы жестко закодировали индексы от 0 до 3.Однако ваш tableView переключается между коллекциями Array и Filter.Более того, данные в коллекции Filter могут изменяться в зависимости от текста в поле поиска.

Вы можете решить это, как написано @Sh_Khan.Но, возможно, лучше бы иметь отфильтрованную коллекцию, привязанную к tableView, и неизмененную коллекцию, содержащую все данные.

Таким образом, вам не нужно проверять, установлен ли isSearching в каждомметод.На самом деле, вам это вообще не нужно.Вам просто нужно сделать следующее:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Filter.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell
    cell.CellLabel.text = Filter[indexPath.row]
    return cell
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        view.endEditing(true)
        Filter = Array.compactMap({ $0 }) // Copies all elements from Array
    } else {
        Filter = Array.filter({ $0.contains(searchBar.text!) })
    }
    TableView.reloadData()
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(Filter[indexPath.row])
}
0 голосов
/ 23 мая 2018

Вам нужно поставить поиск 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])
     }
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...