Search code examples
uitableviewswiftuisearchcontroller

UISearchController in a UIViewController


I'm looking to create similar functionality to Apple's maps application in Swift. Is there anyway to integrate a UISearchController in to a regular view (i.e.: not a UITableView). Dropping one in through Storyboard results in a crash after clicking inside the connected searchbar. Or is there some way I can achieve this outcome with a UITableView?


Solution

  • I added a Search Bar and Search Display Controller in my View Controller in the storyboard. The view controller contains only the search bar and search display controller and does not have it's own TableView. When you add the search bar in your view controller, it sets your view controller as it's delegate automatically.

    Now the Search Bar and Search Display Controller has a table view of itself which it uses to display the search results when you click inside the box and start typing. This table view expects your view controller to provide the implementations of the numberOfRowsInSection and cellForRowAtIndexPath functions for it to display the data properly.

    When you run your project without these and tap inside the search bar, you will get the following error:-

    tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x7fbf63449660 *** Terminating app due to uncaught exception 'NSInvalidArgumentException'

    If you see, the error is at the numberOfRowsInSection method.

    Change your view controller definition from

    class ViewController: UIViewController
    

    to

    class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
    

    and implement the required methods which are:-

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    

    I have just added default return values in the above methods.

    Now if you filter out your data source in your searchviewdelegate methods and set up your number of rows and cell info in the above two methods properly, it should work.

    Hope this helps!