Search code examples
iosuitableviewswift2uisearchcontroller

Programmatically add a UISearchController to a UITableView header in swift 2


In the previous version of my view controller (based on storyboard) the search bar was working good. In the 100% programmatically defined current version (I removed all storyboard references) the search bar has disappeared. I am trying to understand where the problem lies, without success. Any idea?

Here is the faulty code snippet:

let resultSearchController = UISearchController()

override public func viewDidLoad() {
    super.viewDidLoad()

    // No nav bar
    navigationController?.navigationBar.hidden = true

    // — Add table view
    view.addSubview(tableView)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 0).active = true
    tableView.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: 0).active = true
    tableView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: 0).active = true


    // Add search bar as a the table header

    resultSearchController.dimsBackgroundDuringPresentation = false
    resultSearchController.definesPresentationContext = true
    resultSearchController.hidesNavigationBarDuringPresentation = false

    resultSearchController.searchResultsUpdater = self
    resultSearchController.searchBar.sizeToFit()
    resultSearchController.searchBar.delegate = self
    tableView.tableHeaderView = resultSearchController.searchBar

    /// Add refresh control
    refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refreshControl.addTarget(self, action: #selector(BigHeadViewController.refreshTable), forControlEvents: UIControlEvents.ValueChanged)
    tableView.addSubview(refreshControl)  
}

Solution

  • I think the problem might be the first line. You have to specify the "searchResultsController" as part of the initialisation - even if it's nil (to search in place). Try

    let resultSearchController = UISearchController(searchResultsController:nil)