3

In iOS 7, when the user clears the text formerly in a UISearchBar, the blue "Search" button becomes disabled. Is there any way to change this, so it's always enabled? I want the user to be able to hit "Search" even when there is no text, to show all items in the list, instead of filtering it by the search term. (Currently, when the user attempts to clear a former search term, the blue Search button becomes disabled.)

I could trigger a new search in my delegate's searchBarTextDidEndEditing callback, so that the Dismiss keyboard button causes a refreshed list with all results... but ideally I'd like the blue Search button to be available even when there is no text in the field. Is this possible?

Vern Jensen
  • 3,449
  • 6
  • 42
  • 59

2 Answers2

9

Apple changed UISearchBar structure in iOS 7. I have found combined solution for iOS 7 and previous iOS versions.

- (void)searchBarTextDidBeginEditing:(UISearchBar *) bar
{
    UITextField *searchBarTextField = nil;
    NSArray *views = ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0f) ? bar.subviews : [[bar.subviews objectAtIndex:0] subviews];
    for (UIView *subview in views)
    {
        if ([subview isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)subview;
            break;
        }
    }
    searchBarTextField.enablesReturnKeyAutomatically = NO;
}
B.S.
  • 21,660
  • 14
  • 87
  • 109
0

After a quick look through the headers, it looks like what what you're trying to accomplish isn't what they intended UISearchBar to be used for. To get exactly what you want, you'll probably need to work with a normal text field without all the search trimmings.

That said, I have a hack that mostly works. It fills the search bar with a dummy string when it's not in use. When you enter your first character, there's a split-second where the search button is disabled. But for the most part, it gets what you want:

NSString *kDummyString = @" ";

@implementation CDViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchBar.text = kDummyString;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length < 1) {
        searchBar.text = kDummyString;
    }
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range     replacementText:(NSString *)text
{
    BOOL isPreviousTextDummyString = [searchBar.text isEqualToString:kDummyString];
    BOOL isNewTextDummyString = [text isEqualToString:kDummyString];
    if (isPreviousTextDummyString && !isNewTextDummyString && text.length > 0) {
        searchBar.text = @"";
    }

    return YES;
}

@end 
cdownie
  • 239
  • 2
  • 8