如何使用扩展设置 viewController 搜索栏的委托?
Posted
技术标签:
【中文标题】如何使用扩展设置 viewController 搜索栏的委托?【英文标题】:How to set delegate of search bar of viewController using extension? 【发布时间】: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
【问题讨论】:
【参考方案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
【讨论】:
以上是关于如何使用扩展设置 viewController 搜索栏的委托?的主要内容,如果未能解决你的问题,请参考以下文章
如何设置 UIViewController “扩展边缘”属性
如何从小部件扩展导航到 UIKit viewController?
如何将正确的 viewModel 注入单个 viewController
Swift 3:将UIButton扩展添加到ViewController