【问题标题】:How is this implemented in swift 4?这是如何在 swift 4 中实现的?
【发布时间】:2018-08-04 13:25:33
【问题描述】:

我有这个link 用于表格视图中的下拉搜索栏。我能够使用此代码在 tableview 中实现搜索栏

  searchController.searchResultsUpdater = self 
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = ""
    if #available(iOS 11.0, *) {
        navigationItem.searchController = searchController
    } else {
        self.tableView.tableHeaderView = searchController.searchBar
    }
    definesPresentationContext = true
    searchController.searchBar.delegate = self

我现在想实现搜索功能,但是我无法在搜索栏中获取文本值。任何人都可以提供有关如何正确实施此功能的任何提示吗?谢谢你。

编辑:

这是 viewWillAppear 部分,用于在视图显示时隐藏搜索栏。我现在有另一个问题。如果我开始编辑搜索栏完全隐藏在视图中。如果我删除searchController.searchBar.delegate = self,那么搜索栏将不会隐藏。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.tableView.contentOffset = CGPoint(x: 0,y :60.0)
}

【问题讨论】:

  • 我无法在搜索栏中获取文本值。 ?你没有得到什么?
  • 我正在尝试从 func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 打印 searchText。我在这里什么也得不到
  • 我会读它。谢谢
  • @jiren 您是否将 searchController.searchResultsUpdater 设置为您的 ViewController?

标签: swift uitableview uisearchbar uisearchbardelegate


【解决方案1】:

我建议使用UISearchResultsUpdating 协议,而不是设置searchController.searchBar.delegate = self

import UIKit

class MyViewController: UIViewController, UISearchResultsUpdating {

    override func viewDidLoad() {
        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = ""
        searchController.hidesNavigationBarDuringPresentation = false

        if #available(iOS 11.0, *) {
            navigationItem.searchController = searchController
        } else {
            self.tableView.tableHeaderView = searchController.searchBar
        }
        definesPresentationContext = true
        //searchController.searchBar.delegate = self        <--- you don't need this
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchString = searchController.searchBar.text {
            print(searchString)
        }
    }
}

【讨论】:

  • 谢谢。我现在可以获取 searchString 但是我不确定为什么当我单击编辑搜索栏时搜索栏会自动隐藏。
  • @jiren 尝试将此添加到您的 searchController:searchController.hidesNavigationBarDuringPresentation = false 让我知道它是否有帮助,然后我可以编辑我的答案。
  • 这完成了@Teetz 的工作。非常感谢
  • @jiren 很高兴我能帮上忙。编辑了我的答案并添加了这一行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 2020-11-18
  • 2020-11-24
  • 2020-02-17
  • 1970-01-01
  • 2020-05-30
相关资源
最近更新 更多