【问题标题】:How to fix SearchBar as header of UITableView when scrolling?滚动时如何将 SearchBar 修复为 UITableView 的标题?
【发布时间】:2018-10-12 22:09:47
【问题描述】:

我有一个带有 SearchBar 的 TableView,但是当我滚动列表时,顶部栏的搜索栏消失,我需要向上滚动以显示搜索栏。我在谷歌和堆栈溢出尝试了几种解决方案,但没有解决我的问题。

我试过这个:

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

override func viewDidLoad() {
    conteudo = ["Augusto","Luis","Joao","Marina","Taina","Evandra","Miguel","Daniela","Luciano","Patricia","Jose","Vinicius","John","William"]

    currentConteudo = conteudo
    currentConteudo.sort()

    tableView.dataSource = self
    tableView.delegate = self
    tableView.tableHeaderView = searchBar
    tableView.estimatedSectionHeaderHeight = 50
    searchBar.delegate = self
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellSearchCustomer")!
    cell.textLabel?.text = currentConteudo[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return searchBar
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return UITableViewAutomaticDimension
}

滚动:

未滚动:

故事板:

【问题讨论】:

  • 您只想让searchBar 一直可见吗?
  • 是的,它是.....
  • @Augusto,你想在 tableview 向上滚动时滚动搜索栏。?或者,当表格视图向上滚动时,您希望搜索栏不滚动。?
  • 我希望搜索栏永远不会丢失。向上或向下滚动,搜索栏必须始终可见。固定在顶部

标签: ios swift xcode uitableview uisearchbar


【解决方案1】:

如果您希望 searchBar 始终可见,您需要将其移动到 storyboard 中的 tableView 上方。目前在里面。

【讨论】:

  • 不,可以使用像 tableview 的标题视图这样的搜索栏来完成
  • 你需要更清楚地解释你需要什么行为。
  • 我按照教程进行操作,一个是 -> youtube.com/watch?v=4RyhnwIRjpA(19 分钟),他来处理。但对我来说不起作用。
【解决方案2】:

不要直接使用 UISearchBar 作为 tableView 标题,而是使用 UISearchController 并将其添加到 navigationItem.searchController 将解决此问题。

fileprivate let searchController = UISearchController(searchResultsController: nil)

viewDidLoad

searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
definesPresentationContext = true
navigationItem.searchController = searchController

UISearchControllerDelegate让你知道开始搜索:

func updateSearchResults(for searchController: UISearchController) {
    // your search operation
    print("Search text : \(searchController.searchBar.text!)")
}

【讨论】:

    猜你喜欢
    • 2013-08-02
    • 2017-10-14
    • 2018-01-10
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    相关资源
    最近更新 更多