Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar and event fired when 'X' element is tapped

On the UISearchBar, there's an X element that allows you to clear all of the contents at once. Is there a way to get notified when this happens?

UISearchBarDelegate::searchBarCancelButtonClicked is fired only when the "Cancel" button is tapped.

like image 472
Justin Galzic Avatar asked Nov 08 '10 01:11

Justin Galzic


3 Answers

The UISearchBar doesn't have a delegate method for this event. You can nearly get what you want by implementing the textDidChange: method of the callback delegate and checking for an empty string.

I don't recommend it, but there is another possible way. The UISearchBar is composed of a UITextField, which does have a delegate method that is called when the user taps the clear button (textFieldShouldClear:). You can get the UITextField by traversing the UISearchBar's child views:

(this is in the context of a derived UISearchBar class)

- (UIView*) textField
{
    for (UIView* v in self.subviews)
    {
        if ( [v isKindOfClass: [UITextField class]] )
            return v;
    }

    return nil;
}

from here, you could re-assign the UITextField delegate to your own implementation, taking care to forward delegate calls to the old delegate. This way you could intercept textFieldShouldClear:. Or if it turns out the UISearchBar is the delegate for the UITextField it contains you could swizzle the call to textFieldShouldClear:... Not ideal, clearly, but technically feasible.

like image 120
TomSwift Avatar answered Oct 06 '22 00:10

TomSwift


I had the same issue and I solved this issue by using this function.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{
    // This method has been called when u enter some text on search or Cancel the search.
    if([searchText isEqualToString:@""] || searchText==nil) {
        // Nothing to search, empty result.

       [UIView animateWithDuration:0.2 animations:^ {
        //Reposition search bar 
        [_searchBar setFrame:CGRectMake(230, 26, 43, 44)];
        [_searchBar setNeedsLayout];
       }];
    }
}
like image 29
Akhtar Avatar answered Oct 05 '22 23:10

Akhtar


Here is an answer from a previous question, this should do exactly what you want. UISearchbar clearButton forces the keyboard to appear

like image 36
Tozar Avatar answered Oct 06 '22 00:10

Tozar