【问题标题】:Can't get SearchController to show with TableView无法让 SearchController 与 TableView 一起显示
【发布时间】:2020-07-20 07:39:24
【问题描述】:

我正在按照 raywenderlich.com 教程显示我的表格的搜索栏,但我在任何地方都看不到它(是的,我向上滚动)

这是我的代码:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate, UISearchResultsUpdating {
    
    @IBOutlet weak var tableView: UITableView!        
    
    func updateSearchResults(for searchController: UISearchController) {
        let searchBar = searchController.searchBar
        filterContentForSearchText(searchBar.text!)
    }

    var isSearchBarEmpty: Bool {
      return searchController.searchBar.text?.isEmpty ?? true
    }

    func filterContentForSearchText(_ searchText: String) {
      filteredStrings = stockArr.filter { (string: String) -> Bool in
        return string.lowercased().contains(searchText.lowercased())
      }
      tableView.reloadData()
    }
    var filteredStrings: [String] = []

    var searchController : UISearchController!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        

        let searchController = UISearchController(searchResultsController: nil)

        searchController.searchResultsUpdater = self

        searchController.obscuresBackgroundDuringPresentation = false

        searchController.searchBar.placeholder = "Search Candies"

        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
        
        definesPresentationContext = true
  
    }
}

请帮助我,我已经尝试了所有 StackOverflow 解决方案,但没有任何效果,这段代码与我之前的普通 tableview 没有什么不同。

【问题讨论】:

标签: ios swift xcode tableview uisearchcontroller


【解决方案1】:

您可能正在使用ViewController 而不将其嵌入UINavigationController。您必须将其嵌入UINavigationController 以使其显示在UINavigationBar 中。因此,在使用 ViewController 时,如果您以编程方式使用它,请按如下方式使用它。

UINavigationController(rootViewController: ViewController())

如果 ViewController 是在情节提要中创建的,则使用 Editor-> Embed In -> Navigation Controller

【讨论】:

  • 我还没有看到这是你的观点所需要的东西......我在哪里把这段代码放在我的课堂上?
  • 您可能已经在故事板中创建了 ViewController,因此您可以将 ViewController 嵌入到导航控制器中,如上所述。
  • 太棒了,它成功了!我唯一的另一个问题是,当我向上滚动以显示搜索并再次向下滚动时,有没有办法再次隐藏它?
  • 把链接发给我,我一定会看看的。
  • 这很快。会检查的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
  • 2018-01-02
  • 2016-11-14
  • 2020-02-29
相关资源
最近更新 更多