swiftuitableviewuisearchbaruisearchbardelegate

How is this implemented in swift 4?


I have this link for a pull down search bar in a table view. I was able to implement the search bar in the tableview with this code

  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

I would want to implement the search function now however I am not able to get the text value in the searchbar. Can anyone provide any hints on how to properly implement this? thank you.

EDIT:

This is the viewWillAppear part to hide the searchbar when the view shows up. I have another problem now. If I start to edit the searchbar totally hides from the view. if I remove searchController.searchBar.delegate = self then the searchbar wont hide.

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

Solution

  • Instead of setting searchController.searchBar.delegate = self i would recommend to use the UISearchResultsUpdating protocol.

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