如何使用扩展设置视图控制器搜索栏的委托



我创建了导航自定义类,我想装饰它,我采用了 NavDecoration.swift 类并声明了扩展,该扩展显示在下面的代码中,我添加了搜索条形码以及在此函数中,我想在此扩展中设置搜索栏委托,但它的给出错误无法将类型"UIView控制器"分配给类型"UISearchBarDelegate

 extension UINavigationController {
 func makeBlackNavigationbar (viewController: UIViewController, animated: Bool) {
 viewController.navigationController?.navigationBar.backgroundColor? = UIColor.blackColor()
    let add = UIBarButtonItem(barButtonSystemItem: .Add, target: viewController, action: "addTapped")
    let play = UIBarButtonItem(title: "Play", style: .Plain, target: viewController, action: "addTapped")
   viewController.navigationItem.rightBarButtonItems = [add, play]
    let left = UIBarButtonItem(barButtonSystemItem: .Add, target: viewController, action: "addTapped")
    viewController.navigationItem.leftBarButtonItems = [left]
       let searchBar = UISearchBar(frame: CGRectZero)
        searchBar.placeholder = "Search"
        searchBar.delegate = viewController
        viewController.navigationItem.titleView = searchBar
}}

您必须符合UISearchBarDelegate协议:

extension UINavigationController : UISearchBarDelegate {
   ...
}

**我只更改了几行代码 **

  extension UIViewController : UISearchBarDelegate {
func makeBlackNavigationbar (viewController: UIViewController, animated: Bool) {
    viewController.navigationController?.navigationBar.backgroundColor? = UIColor.blackColor()
    let add = UIBarButtonItem(barButtonSystemItem: .Add, target: viewController, action: "addTapped")
    let play = UIBarButtonItem(title: "Play", style: .Plain, target: viewController, action: "addTapped")
    viewController.navigationItem.rightBarButtonItems = [add, play]
    let left = UIBarButtonItem(barButtonSystemItem: .Add, target: viewController, action: "addTapped")
    viewController.navigationItem.leftBarButtonItems = [left]
       let searchBar = UISearchBar(frame: CGRectZero)
        searchBar.placeholder = "Search"
        searchBar.delegate = viewController
        viewController.navigationItem.titleView = searchBar
}}

最新更新