ios - 无法将 UISearchController 添加到 UIViewController

标签 ios swift uitableview uiviewcontroller uisearchcontroller

我正在尝试将 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 一起使用?

最佳答案

确保您的 UIViewController 符合协议(protocol) UISearchBarDelegateUISearchResultsUpdating

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

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

关于ios - 无法将 UISearchController 添加到 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32263093/

相关文章:

ios - 根据内容动态调整表格 View 单元格的高度 - iOS Swift

ios - 抓取特定文本标签的值并在 didSelectRowAtIndexPath 中制作 json

ios - Firestore 使用 for 循环查询多个文档

ios - 可选类型 CGFloat 的值?没有拆封,你是想用吗!或者?

ios - UITableView:未调用 "didDeselectCell"方法,尽管单元格被取消选择

ios - 索引 NSFetchedResultsController

ios - 如何在不点击通知的情况下收到 FCM 通知时打开(启动)应用程序

IOS:管理缓存的项目

ios - "The file couldn’ t被打开的解决办法是什么。"UserInfo={NSURL=ftp :/xxxx:xxx@2011@ftp. xxx.com :21/}?

ios - Firebase 数据比较 swift