mvasco
mvasco

Reputation: 5101

closing UISearchBar after showing results

In a UITableView I have a hidden UISearchBar as default behaviour at app launch. Later, if the user needs to search for a term, there is UIButton action that shows the UISearchBar and the keyboard. The problem I have is that after executing the search, I don't know how to cancel the search or to close the UISearchBar. If the user clicks on the keyboard Search button, the keyboard disappears, that is OK, but if the user clicks on the UISearchBar Cancel button, anything happen.

This is my code to hide the UISearchBar:

- (void)hideSearchBar {

    CGRect newBounds = self.tableView.bounds;
    if (self.tableView.bounds.origin.y < 44) {
        newBounds.origin.y = newBounds.origin.y + self.searchBar.bounds.size.height;
        self.tableView.bounds = newBounds;

    }
}

And this my code to show the UISearchBar and the keyboard:

- (IBAction)showSearchBar:(id)sender {


    [self.searchBar becomeFirstResponder];
}

Upvotes: 1

Views: 719

Answers (2)

iPatel
iPatel

Reputation: 47089

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar

Above is delegate method of UISearchBar, it's use for manage UISearchBar when you press on cancel button.

Put you stuff of code as per your requirement.

Such like

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @""; // clear text of search
    [searchBar resignFirstResponder]; // keyBoard is hide
    [self.searchBar setShowsCancelButton:NO animated:YES]; // remove cancel button from searchBar
   // Etc..
}

EDITED :

You can declare and access UISearchBar such like,

@interface myViewController : UIViewController <UISearchBarDelegate, UISearchBarDelegate> // add delegate and datasource to .h file

@property (nonatomic, strong) UISearchBar *searchBar;

And .m file creation of UISearchBar

self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f,38.0f,320.0f,0.0f)]; // set frame as you want.
[self.searchBar sizeToFit];
self.searchBar.delegate = self;
self.searchBar.tintColor = [UIColor colorWithRed:(93/255.f) green:(156/255.f) blue:(13/255.f) alpha:1.0f]; // set color as you want.
[self.view addSubview:self.searchBar];

Upvotes: 1

Akhilrajtr
Akhilrajtr

Reputation: 5182

Try this,

Use searchBarCancelButtonClicked: delegate method of UISearchBar and call hideSearchBar

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { 

    [searchBar setText:@""];
    [searchBar resignFirstResponder];
    [self hideSearchBar];
}

Add

- (void)viewDidLoad {
    ...
    self.searchBar.delegate = self;
}

Upvotes: 1

Related Questions