0
votes

I have a UISearchBar and a UITableView on a view controller in my storyboard. The search bar is above the tableview so that it does not scroll. My problem is that the initialization of a UISearchController creates its own SearchBar instance that is not the same as the one I have manually added and positioned on my storyboard.

How do I set my storyboard SearchBar to be the one created for me by my UISearchController?

class ITSearchController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {

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

    // So that the search results are displayed in the current controllers table view
    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true

        // This didn't work
        //var view = self.view.viewWithTag(777)
        //view = searchController.searchBar

        // This works but isn't what I want
        //tableView.tableHeaderView = searchController.searchBar

        // This works but places it in the nav section. Not what I want.
        // self.navigationItem.titleView = searchController.searchBar

        // This is what I want but doesn't work. Basically make the search bar on my storyboard equal to the one created.
        searchBar = searchController.searchBar

    }
}
1

1 Answers

2
votes

You cannot use the search bar you have placed on the storyboard with UISearchController since UISearchController provides its own storyboard.

As an alternative, replace the search bar in the storyboard with a UIView and then add the search bar provided by the UISearchController as a subview to that UIView.

class ITSearchController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchView: UIView! // make this UIView

// So that the search results are displayed in the current controllers table view
let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true

    // This should work
    searchView.addSubview(searchController.searchBar)

}
}

This would give you the same behavior.