iphonekeyboarduisearchbarfirst-responder

iphone UISearchBar Done button always enabled


I have a UIViewController with a UISearchBar. I have replaced the Search Button by a Done button.

However, when one taps on the searchbar, the Done button is initially disabled. This occurs until one enters any character.

What I want to do is to have this Done button always enabled, such that if i tap on it i can inmediately dismiss the keyboard.

Any help? it would be highly appreciated.

I have on my UIViewController

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar  
{   
    return YES;  
}  

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}  

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText  
{  
    if (searchBar.text.length == 0)  
    {  
        //[self fixOrientation];  
        [searchBar resignFirstResponder];  
    }   
    else  
    {  
        NSLog(@"typed");  
    }  
}  


-(void)searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar  
{  
    NSLog(@"began");  // this executes as soon as i tap on the searchbar, so I'm guessing this is the place to put whatever solution is available  
}  

Solution

  • Nowadays UISearchBar conforms to UITextInputTraits. You can simply set:

    searchBar.enablesReturnKeyAutomatically = NO;
    

    WARNING: While this compiles for iOS 7.0, it will crash at runtime. It only works for >=7.1.

    The docs are not clear on this one, as only since 7.1, the UISearchBar implements the UITextInputTraits protocol, but it is not noted since which iOS version the protocol is adopted.