pushVC из отфильтрованного tableView - PullRequest
0 голосов
/ 26 января 2019

Я добавил работающий SearchBar в свой tableView - если я щелкаю по ячейке из неотфильтрованного tableView, он попадает ко мне в правый второй VC (контроллер чата) ... но если я щелкаю по ячейке из фильтрованного tableView,Меня подталкивают ко второму виртуальному контуру из ячейки нефильтрованного табличного представления - поэтому, если я отфильтрую табличное представление и щелкну ячейку в фильтруемой таблице, я фактически нажму на ячейку из нефильтрованного табличного представления - надеюсь, вы понимаете мою проблему ...

Если здесь нет примера: В третьей ячейке unfilteredTableView отображается имя «Alex3», теперь, когда я нажимаю на ячейку, я попадаю в чат с «Alex3» - но если яотфильтруйте tableView для "John3" и нажмите на третью ячейку. Я не попадаю в чат с "John3", но в чат с "Alex3"

Это код:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    searchController.dismiss(animated: true, completion: nil)
    let user = self.users[indexPath.row]
    let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
    chatLogController.user = user
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        self.navigationController?.pushViewController(chatLogController, animated: true)
    }
}

Код для панели поиска / контроллера:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isFiltering() {
        return filtered.count
    }
    return users.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell
    var user = users[indexPath.row]
    cell.textLabel?.text = user.name
    if isFiltering() {
        user = filtered[indexPath.row]
    } else {
        user = users[indexPath.row]
    }
    cell.textLabel!.text = user.name

    return cell
}

//UISearchBar
func searchBarIsEmpty() -> Bool {
    // Returns true if the text is empty or nil
    return searchController.searchBar.text?.isEmpty ?? true
}

func isFiltering() -> Bool {
    return searchController.isActive && !searchBarIsEmpty()
}

func filterContentForSearchText(_ searchText: String, scope: String = "All") {
    filtered = users.filter({( user : User) -> Bool in
        return (user.name?.lowercased().contains(searchText.lowercased()))!
    })
    tableView.reloadData()
}


}

extension NewMessageController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResults(for searchController: UISearchController) {
    filterContentForSearchText(searchController.searchBar.text!)
    }
}

1 Ответ

0 голосов
/ 26 января 2019

Здесь не так много, чтобы помочь, если бы вы могли поделиться логикой фильтрации, которая будет полезна при анализе проблемы, но из того, что вы поделились, у меня есть предложение.

let user = self.users[indexPath.row]

Проверьте, выбираете ли вы пользователя из отфильтрованного списка, а не из исходного списка. Это может помочь

Ниже приведен пример кода, который может помочь

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    searchController.dismiss(animated: true, completion: nil)
    var user : User?
    if isFiltering() {
        user = filtered[indexPath.row]
    } else {
        user = users[indexPath.row]
    }
    let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
    chatLogController.user = user
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        self.navigationController?.pushViewController(chatLogController, animated: true)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...