ios - 将数据传递到搜索栏

标签 ios swift uisearchbar

我有 2 个互相喜欢的 viewController。第一个viewController有一个collectionView作为按钮,所以当你点击collectionView时,它会通过segue引导你到第二个viewContoller。

  @IBAction func presedCollectionViewButton(_ sender: Any) {
    performSegue(withIdentifier: "segue", sender: self)
  }

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let destinationVC = segue.destination as! AllCategoriesViewController
    destinationVC.filterText = test

}

然后我将数据传递到第二个controllView中的searchBar,以便在执行执行segue后过滤tableView,但它不会直接过滤tableView,为了查看我传递的filterText,我必须单击在 viewController 的 searchBar 上。

extension AllCategoriesViewController: UISearchBarDelegate {

     func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchBar.text = filterText
        filteredCategory = allcotegoryLabel.filter({$0.categoryName.prefix(searchText.count) == searchText})
        isSearch = true
        allCategoriesTableView.reloadData()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        isSearch = false
        searchBar.text = ""
        allCategoriesTableView.reloadData()
    }
}

所以我的问题是如何解决这个问题并让它在执行预成型segue后过滤tableView?

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "allCategories", for: indexPath) as! allCategoriesTableViewCell
    if isSearch {
       cell.allCategoriesLabel.text = filteredCategory[indexPath.row].categoryName
    } else {
       cell.allCategoriesLabel.text = allcotegoryLabel[indexPath.row].categoryName
    }
    return cell
}

这是 isSearch 的一些用法

最佳答案

您应该将搜索栏文本设置为变量而不是搜索栏。然后,在viewDidLoad()方法中设置搜索栏文本,然后在viewDidLoad方法中刷新tableView。如果这不起作用,您可以在 viewDidAppear 中尝试相同的操作。

关于ios - 将数据传递到搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819617/

相关文章:

ios - 无法在另一个类中设置 UIButton 目标?

ios - 创建 Shazam 类型 UI ios Swift

ios - iOS中如何通过storyboard将UISearchBar添加到NavigationBar

ios - 在 iOS 9 中检查互联网连接失败?

ios - 在 Swift 中覆盖子类中的属性的正确方法是什么?

ios - Objective-C - 即使应用了 sqlite3_close(),sqlite3_open 内存泄漏

iphone - 寻找一种更好的方法来隐藏 View 顶部的搜索栏

ios - 使用 TextField 标记和保存数据

uiwebview - Swift:webView 项目中的 ViewController 错误

UISearchBar 范围按钮的 iOS 可视化更改