如何在Swift 4中实现?

时间:2018-08-04 13:25:33

标签: swift uitableview uisearchbar uisearchbardelegate

我有这个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)
}

1 个答案:

答案 0 :(得分:2)

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

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)
        }
    }
}