skip to Main Content

I am trying to create a custom UISearchBar, but am having trouble when trying to use the delegate methods of a UISearchBar. I am using the following code but it is not working? What am I doing wrong?

class CustomSearchBar: UISearchBar, UISearchBarDelegate {
    
    var searchDelegate: UISearchBarDelegate

    init(del: UISearchBarDelegate) {
        self.searchDelegate = delegate
        super.init(frame: .zero)
        sizeToFit()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print(searchText)
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    After trying a couple things I figured out a way around accessing the delegate. I used searchTextField.addTarget(self, action: #selector(searchBar(_:)), for: .editingDidEnd). This allows me to access when the text was changed in the UISearchBar.


  2. The class that should implement the UISearchBarDelegate protocol is the ViewController where you will display this search bar. In the view controller you would have something like this:

    class VC: UIViewController {
    
        let searchBar = CustomSearchBar()
    
        searchBar.delegate = self
    }
    
    extension VC: UISearchBarDelegate {
        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            print(searchText)
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search