无法将 UISearchController 添加到 UIViewController

Mor*_*Man 3 uitableview uiviewcontroller ios swift uisearchcontroller

我正在尝试将 a 添加UISearchController到以编程方式创建UITableViewUIViewController类中。这是我的代码:

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)

}
Run Code Online (Sandbox Code Playgroud)

我得到的两个错误是

 - 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?
Run Code Online (Sandbox Code Playgroud)

当我的类被子类化时,此代码有效UITableViewController。那么为什么它不能与UIViewController?

pxl*_*hpr 5

确保您UIViewController符合协议UISearchBarDelegateUISearchResultsUpdating.

class YourViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating {
    // …truncated
}
Run Code Online (Sandbox Code Playgroud)

UITableViewController 在幕后自动执行此操作。