Search code examples
iosswiftprotocols

Making search bar notify the viewController that user is about to search


I am implementing a search feature in my app. The app consists of a view controller and a custom class that handles the search logic. This custom class is called SearchController.

My goal is to make the searchBar notify the view controller when the user is about to begin searching (exactly the same behaviour as the UISearchBarDelegate method searchBarShouldBeginEditing).

Normally, you would just declare searchBarShouldBeginEditing inside SearchController but I am trying to call this method from inside the viewController because I want something in my view to change when this event happens (and thus the viewController should be handling it, not the searchController).

SearchController class:

class SearchController: NSObject, UISearchBarDelegate {

    let searchBar = UISearchBar()
    var searchButton = UIBarButtonItem? = nil

    /* Other irrelevant class properties */

    func setup() {
        searchBar.delegate = self
        /* other setup */
    }
}

ViewController class:

class ViewController: UIViewController {

    private let searchController = SearchController()  

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.delegate = self
        searchController.setup()
    }

    /* setup a tableview to display results... this part of the implementation works fine */
}

I omitted the majority of these two classes because the search feature already works. The only thing I am struggling with is finding a way to let viewController know when the user is about to begin typing into the search field.

I tried making viewController implement UISearchBarDelegate but I am already making SearchController implement UISearchBarDelegate so why can't I access the delegate methods inside viewController?

I hope I made myself clear, I can clarify this post further if necessary. I have been tearing my hair out trying to figure this out on my own.


Solution

  • Ok, a searchBar cannot have 2 delegates, so you're gonna have to find a way to work around that.

    One way to go about this is this:

    protocol SearchControllerDelegate: class{
        func searchBarDidBeginEditing()
    }
    
    class SearchController: NSObject, UISearchBarDelegate {
    
        weak var delegate: SearchControllerDelegate?
    
        private let searchBar = UISearchBar()
    
        func setup() {
            searchBar.delegate = self
        }
    
        func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
            delegate?.searchBarDidBeginEditing()
        }
    
    }
    
    class ViewController: UIViewController, SearchControllerDelegate{
    
        var searchController = SearchController()
        func setUP(){
            self.searchController.delegate = self
        }
    
        func searchBarDidBeginEditing() {
            /// perform some action here
        }
    
    }