Search code examples
ioscocoa-touchuisearchbar

How to know when search bar text changes


I have a search bar and I need to get a notification when the bar text changes, how can I do that? I need to reload the table view every time the string value of the search bar changes


Solution

  • Follow the below steps to get it done

    Add Delegate methods for your View Controller

    ViewController: UISearchBarDelegate, UISearchDisplayDelegate
    

    Create IBOutlet for your searchBar

    @IBOutlet weak var searchBarVar: UISearchBar!
    

    Assign Delegates as self to searchBar in viewDidLoad.

    override func viewDidLoad() {
        super.viewDidLoad()
        
        searchBarVar.delegate = self
    }
    

    Implement the textDidChange delegate method

    Swift 4:

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print("searchText",searchText)
    }
    

    ObjC

    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;