【问题标题】:Cannot add UISearchController to UIViewController无法将 UISearchController 添加到 UIViewController
【发布时间】:2015-08-28 03:56:05
【问题描述】:

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

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?

【问题讨论】:

  • 你需要符合UISearchBarDelegate
  • 您是否将代理添加到视图控制器? class ViewController: UIViewController, UISearchResultsUpdating, UISearchBarDelegate
  • 谢谢!这是我的问题。

标签: ios swift uitableview uiviewcontroller uisearchcontroller


【解决方案1】:

确保您的UIViewController 符合UISearchBarDelegateUISearchResultsUpdating 协议。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多