anoop
anoop

Reputation: 59

How to cancel the keyboard in UISearchbar?

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!

Upvotes: 3

Views: 5931

Answers (3)

Ahmed Hossny
Ahmed Hossny

Reputation: 272

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;
}

Upvotes: 1

tux91
tux91

Reputation: 1684

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.

Upvotes: 1

Aurum Aquila
Aurum Aquila

Reputation: 9126

Use this:


[UISearchBar resignFirstResponder];

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

Upvotes: 9

Related Questions