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