UISearchBar automatically resizes and changes frame

Moxy picture Moxy · Jan 7, 2014 · Viewed 8k times · Source

I have an issue with a search bar that behaves in a strange way when it becomes a firstResponder and when it resigns.

The search bar is added as the header of a table view

self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f)];
self.searchBar.translucent = NO;
self.searchBar.barTintColor = [UIColor grayColor];
self.tableView.tableHeaderView = self.searchBar;

self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar
                                                          contentsController:self];
self.searchController.searchResultsDataSource = self;

The view controller is set a left panel of JASidePanelController and it hides the center panel when the keyboard shows or hides :

- (void)keyboardWillAppear:(NSNotification *)note
{
    [self.sidePanelController setCenterPanelHidden:YES
                                          animated:YES
                                          duration:[[note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    self.searchBar.showsCancelButton = YES;
}

- (void)keyboardWillDisappear:(NSNotification *)note
{
    [self.sidePanelController setCenterPanelHidden:NO
                                          animated:YES
                                          duration:[[note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    self.searchBar.showsCancelButton = NO;
}

Normal state Normal state

When the search bar becomes a firstResponder it either moves about a point up or point down randomly

Point up Point down



And When the search bar resigns it animates up to reach the window origin and then back to its natural frame

Stretching up

Reaching origin

Here is a sample project reproducing the bug.

EDIT :

As per @kwylez suggestion, the unwanted animation that the search bar makes when it resigns can be avoided by:

self.searchBar.clipsToBounds = YES;

Answer

Muhammad Ahsan picture Muhammad Ahsan · May 17, 2015

I solved this issue by creating a UIView with ClipBounds sets to YES and then add subview the searchbar inside it. Then include it in tableview header. its working now.

Thanks