简体   繁体   中英

Search empty string in searchbar : Objective-c

I want to allow user to search an empty string in searchbar. Whenever user enters any text the search button of keyboard becomes active. However if searchbar is empty then search button of keyboard is inactive. I have tried on below delegates but didn't worked.

- (void) searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {

  ... 
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
  ...
}

Scrrenshot

Any fix for this problem? Sure +1 for correct answer.

A simple way set to search text like below

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    //Add a blank character to hack search button enable
    searchBar.text = @" ";
}

However this looks bad, its exactly what you want.

You need to customize UITextField inside UISearchBar

    @try {
        for (id object in [[[search subviews] firstObject] subviews])
        {
            if (object && [object isKindOfClass:[UITextField class]])
            {
                UITextField *textFieldObject = (UITextField *)object;
                //textFieldObject.returnKeyType = UIReturnKeySearch;
                textFieldObject.enablesReturnKeyAutomatically = NO;
                break;
            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"Error while customizing UISearchBar");
    }
    @finally {

    }

Here, search is UISearchBar .

Hope this will work for you ! :)

FYI, this is working great in iOS7 and 8.1.1 too. Not checked with < 7.0 and > 8.1.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM