Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot add UISearchController to UIViewController

I am trying to add a UISearchController to a programatically created UITableView, in a UIViewController class. Here is my code:

var resultSearchController = UISearchController()

var myTableView = UITableView()

override func viewDidLoad() {
    super.viewDidLoad()

    myTableView.frame = CGRectMake(0, 0, view.bounds.width, view.bounds.height)
    myTableView.delegate = self
    myTableView.dataSource = self

    myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self //ERROR
        controller.searchBar.delegate = self //ERROR
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        self.myTableView.tableHeaderView = controller.searchBar

        return controller
    })()

    UIApplication.sharedApplication().keyWindow?.addSubview(myTableView)

}

The two errors I get are

 - Cannot assign a value of type 'ViewController' to a value of type 'UISearchBarDelegate?
 - Cannot assign a value of type 'ViewController' to a value of type 'UISearchResultsUpdating?

This code works when my class is subclassed with UITableViewController. So why doesn't it work with UIViewController?

like image 705
MortalMan Avatar asked Aug 05 '26 11:08

MortalMan


1 Answers

Make sure your UIViewController is conforming to the protocols UISearchBarDelegate and UISearchResultsUpdating.

class YourViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating {
    // …truncated
}

UITableViewController automatically does this behind the scenes.

like image 131
pxlshpr Avatar answered Aug 07 '26 02:08

pxlshpr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!