Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone UISearchBar Done button always enabled

Tags:

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  
}  
like image 851
David Homes Avatar asked Jan 18 '11 19:01

David Homes


1 Answers

You can get around this by looping around the subviews in the UISearchBar until you find the text field. Its then just a matter of setting "enablesReturnKeyAutomatically" to NO. Incidentally the following code also is useful for setting the keyboard type.

  // loop around subviews of UISearchBar
  for (UIView *searchBarSubview in [searchBar subviews]) {    
    if ([searchBarSubview conformsToProtocol:@protocol(UITextInputTraits)]) {    
      @try {
        // set style of keyboard
        [(UITextField *)searchBarSubview setKeyboardAppearance:UIKeyboardAppearanceAlert];

        // always force return key to be enabled
        [(UITextField *)searchBarSubview setEnablesReturnKeyAutomatically:NO];
      }
      @catch (NSException * e) {        
        // ignore exception
      }
    }
  }
like image 76
AndyDunn Avatar answered Oct 02 '22 07:10

AndyDunn