iosswiftxcodedelegatesuisearchbar

How to use delegate methods in a custom UISearchBar subclass


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

Solution

  • 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.