user3162102
user3162102

Reputation: 105

Text in search bar disappears when search button on keyboard is clicked in iPhone

After typing text in the search bar of iPhone, when search button is clicked on the keyboard, the text disappears. I've added <UISearchDisplayDelegate, UISearchBarDelegate> and BOOL isSearching;

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
     NSLog(@"Text change - %d",isSearching);
     NSString *str = searchBar.text;
     self.searchDisplayController.searchBar.text = str;
     //Remove all objects first.
     [filteredArray removeAllObjects];

     if([searchText length] != 0) {
         isSearching = YES;
         [self searchTableList];
     }
     else {
         isSearching = NO;
     }
     [self.tableView1 reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
  NSLog(@"Cancel clicked");
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
   [self searchTableList];
   [searchBar resignFirstResponder];
}
- (void)searchTableList {
    searchString = searchBar.text;

    for (NSString *tempStr in tableData) {
        NSComparisonResult result = [tempStr compare:searchString options:   (NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
        if (result == NSOrderedSame) {
            [filteredArray addObject:tempStr];
        }
    }
}

Upvotes: 1

Views: 1293

Answers (3)

awex
awex

Reputation: 149

Swift 5

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
}

Upvotes: 0

Pawan Ahire
Pawan Ahire

Reputation: 199

Swift 4.0:

I had the same issue, but I resolved by defining the UISearchBarDelegate method i.e. searchBarTextDidEndEditing

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

}

Without writing any code in method. I hope this answer will help you.

Upvotes: 2

mlabraca
mlabraca

Reputation: 912

I had the same issue with UISearchController.
I prevented the search controller clearing the text storing it in a String and later, after deactivating the controller, assigning the stored text to the search bar.

Objective C:

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *text = searchBar.text;
    [self.searchController setActive:NO animated:YES];
    self.searchController.searchBar.text = text;
}

Swift 2.X:

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    let text = searchBar.text
    searchController.active = false
    searchController.searchBar.text = text
}

Hope it helps.

Upvotes: 0

Related Questions