How do you hide/show UISearchBar's scope bar with animation?

zekel picture zekel · Jun 17, 2010 · Viewed 16.9k times · Source

I want to show no scope bar when the table is empty (before the search bar edits for the first time), no scope bar when it's editing, and finally show it when editing done. I know about the UISearchBarDelegate protocol, but I don't know how to show/hide the scope bar with animation. I know UISearchBar has setShowsScopeBar:, but no setShowsScopeBar:animated: the way it does for setShowsCancelButton:animated.

Edit It's important that to call [searchBar sizeToFit] after showing/hiding the scope bar. Is there a good way to animate this? (Should I do this? It doesn't appear to work.)

Answer

fulvio picture fulvio · May 30, 2011

Here's how to make the cancel button and the scope bar to be displayed only while editing.

Complete code with the small bonus of animating the cancel button’s (dis)appearance:

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsScopeBar = YES;
    [searchBar sizeToFit];
    [searchBar setShowsCancelButton:YES animated:YES];

    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    searchBar.showsScopeBar = NO;
    [searchBar sizeToFit];
    [searchBar setShowsCancelButton:NO animated:YES];

    return YES;
}

EDIT - Version Swift 3

public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
    searchBar.showsScopeBar = true
    searchBar.sizeToFit()
    searchBar.setShowsCancelButton(true, animated: true)

    return true
}

public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    searchBar.showsScopeBar = false
    searchBar.sizeToFit()
    searchBar.setShowsCancelButton(false, animated: true)

    return true
}

Source: http://www.alexandre-gomes.com/?p=418