如何使用扩展名设置viewController的搜索栏的委托?

时间:2016-05-25 13:02:15

标签: ios objective-c iphone cocoa-touch swift2

我创建了导航自定义类,我想装饰它,我拿了NavDecoration.swift类并声明了下面代码中显示的扩展名,我在这个函数中添加了搜索条形码,我想设置搜索栏代表这个扩展但它的给出错误不能指定类型'UIViewController'来键入'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
}}

2 个答案:

答案 0 :(得分:2)

您必须遵守UISearchBarDelegate协议:

extension UINavigationController : UISearchBarDelegate {
   ...
}

答案 1 :(得分:1)

**我通过改变几行代码来完成**

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