Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set delegate of search bar of viewController using extension?

I created navigation custom class and i wanted to decorate it, I took NavDecoration.swift class and declared extension which has shown in below code, I added search bar code as well in this function, I wanted to set search bar delegate in this extension but its giving error can not assign of type 'UIViewController ' to type '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
}}
like image 593
IOSDev Avatar asked May 25 '16 13:05

IOSDev


2 Answers

You have to conform to UISearchBarDelegate protocol :

extension UINavigationController : UISearchBarDelegate {
   ...
}
like image 104
stefos Avatar answered Oct 02 '22 06:10

stefos


**I have done by changing just few line of code **

  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
}}
like image 31
IOSDev Avatar answered Oct 02 '22 07:10

IOSDev