3

I'm using UISearchBar in my application and it serves as both an edit field as well as a search. So when I want to disappear the keyboard I have to use cancel button in UISearchBar but I can't have that cancel button on screen, so how could T make keyboard disappear when not used without using cancel button. Please help me as i'm new to iPhone application development.

Thanks in advance!

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
anoop
  • 59
  • 1
  • 2
  • 3

3 Answers3

9

Use this:


[UISearchBar resignFirstResponder];

Just replace the word UISearchBar with the name of the object you have created.

Aurum Aquila
  • 9,126
  • 4
  • 25
  • 24
  • 5
    I thought I had this problem, but actually I needed to override disablesAutomaticKeyboardDismissal because I was using a UIModalPresentationPageSheet view. Just mentioning it here in case others find this as hard to track down as I did. – Bryan Dec 25 '11 at 22:48
  • 1
    Sorry, should have said UIModalPresentationFormSheet – Bryan Dec 25 '11 at 23:23
  • Excellent comment @Bryan -- that was my issue. – Ralphleon Feb 21 '13 at 20:00
1

Are you looking for ways you can dismiss the keyboard or how to actually do that programmatically? If programmatically, then [UISearchBar resignFirstResponder]. If you are looking for a possible way for the user to achieve that you can either make the return button on the keyboard resign its first responder status when pressed, or attach a UIGestureRecognizer to your view and set it up so that when the user clicks outside the keyboard, this keyboard goes away.

tux91
  • 1,674
  • 10
  • 16
1

simply all you need to do is to get UITextfield control from the UISearchbar and then set UITextfield's delegate to whatever delegate that will perform -(void) textFieldShouldReturn:(UITextField *)textField

-(void)viewDidLoad{    
    UIView * subView;
    NSArray * subViews = [searchbar subviews];
    for(subView in subViews)
    {
        if( [subView isKindOfClass:[UITextField class]] )
        {
           ((UITextField*)subView).delegate=self;
            ((UITextField*)subView).returnKeyType=UIReturnKeyDone;
            break;
        }
    }
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return TRUE;
}
itsaboutcode
  • 24,525
  • 45
  • 110
  • 156
Ahmed Hossny
  • 272
  • 4
  • 12