Improved Swift 4:
Assuming you already match UISearchBarDelegate , this is an improved version of Swift 4 VivienG's answer :
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.reload(_:)), object: searchBar) perform(#selector(self.reload(_:)), with: searchBar, afterDelay: 0.75) } @objc func reload(_ searchBar: UISearchBar) { guard let query = searchBar.text, query.trimmingCharacters(in: .whitespaces) != "" else { print("nothing to search") return } print(query) }
The goal of the implementation of cancelPreviousPerformRequests (withTarget :) is to prevent the continuous reload() call for each change in the search string (without adding it if you typed "abc", reload() will be called three times depending on the number of characters added).
improvement : the reload() method has a sender parameter, which is a search string; Thus, access to its text or any of its methods / properties would be available with the declaration of it as a global property in the class.
Ahmad F Dec 22 '17 at 17:35 2017-12-22 17:35
source share