无法将UISearchController添加到UIViewController

时间:2015-08-28 03:56:06

标签: ios swift uitableview uiviewcontroller uisearchcontroller

我正在尝试在UISearchController课程中以编程方式创建的UITableView添加UIViewController。这是我的代码:

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)

}

我得到的两个错误是

 - 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?

当我的类使用UITableViewController进行子类化时,此代码有效。那么为什么它不适用于UIViewController?

1 个答案:

答案 0 :(得分:4)

确保您的UIViewController符合协议UISearchBarDelegateUISearchResultsUpdating

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

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