【问题标题】:How to set delegate of search bar of viewController using extension?如何使用扩展设置 viewController 搜索栏的委托?
【发布时间】:2016-05-25 13:02:14
【问题描述】:

我创建了导航自定义类,我想装饰它,我使用 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
}}

【问题讨论】:

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


    【解决方案1】:

    你必须符合 UISearchBarDelegate 协议:

    extension UINavigationController : UISearchBarDelegate {
       ...
    }
    

    【讨论】:

    • 我已经准备好了,当我做 searchBar.delegate = viewController 时,它给了我同样的错误,不能将类型“UIViewController”分配给类型“UISearchBarDelegate”
    • 您指定 UiViewController 而不是 UINAvigationController 作为委托。如果您的扩展名如上,则必须设置 searchBar.delegate = viewController.navigationController 。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      相关资源
      最近更新 更多