Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar going to the view's top when I click on it

I have a UITableView which doesn't reach the entire view. Approximatively, the UITableView is two times smaller than the view.

Then, I add "Search Bar and Search Display Controller" to the UITableView from the Object library. So, to visualize, the searchBar appears at the screen's center.

Here's my view :

enter image description here

My problem : When I click into the search field to do my research, the searchBar is going to the top of the view, in place of the navigation bar ! And the transition is very awful... How can I constraint the searchBar to stay in its initial place ?

like image 555
Jonathan F. Avatar asked Dec 10 '13 12:12

Jonathan F.


1 Answers

The problem is related to the search display controller. You don't have the control over the animation and it doesn't seem to handle it well when there's a view sitting on top of your TableView. We had the same exact problem and the easiest way we fixed it is by replacing the Search Display Controller by a simple Search Bar in the Storyboard.

That means your class will now have to implement the delegate method of the search bar to work properly.

To animate properly, simply override the searchBarTextDidBeginEditing and searchBarTextDidEndEditing like so:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.origin.y = tableViewFrame.origin.y - self.yourHeaderView.bounds.size.height;
[UIView animateWithDuration:0.25
                 animations:^{ self.tableView.frame = tableViewFrame; }];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.origin.y = tableViewFrame.origin.y + self.yourHeaderView.bounds.size.height;
[UIView animateWithDuration:0.25
                 animations:^{ self.tableView.frame = tableViewFrame; }];
}

Simply put, you just move the table view frame over the view based on it's height. The animation makes it smoother and cleaner.

like image 193
Gabriel Cartier Avatar answered Sep 25 '22 13:09

Gabriel Cartier