Ali
Ali

Reputation: 1436

How to animate correctly UISearchbar within a custom view with a header view and a UITableview?

I have a custom UIViewController inited from a nib file with the following view hierarchy:

Nib

...where on the left side orange area is a "header view" with two UIButtons and an UILabel at the center and blue area is an UITableView; all under a single UIView.

At run–time this would render more or less like below:

Render

At this point, whenever user will tap on the search bar, I would expect hiding both navigation bar and header view with search bar moved to the top of the window.

However this isn't the case, because navigation bar will automatically will get out of the window and the header view will move to top, but still will stay in the scene; rest will stick to their original places.

At this point I had to add the following code in order to move header view out of the window:

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];

    CGRect frame = self.headerView.frame;
    frame.origin.y -= frame.size.height;
    self.headerView.frame = frame;

    [UIView commitAnimations];
}

which will result to:

Search

... As you may have already noticed header view will move just fine, but the search bar will stick to its original position.

I tried to reposition both self.view or search table view, but no luck there.

What should I do? Thanks.

Upvotes: 0

Views: 2200

Answers (1)

Ali
Ali

Reputation: 1436

Make sure you implement searchDisplayControllerWillBeginSearch: and searchDisplayControllerWillEndSearch: of UISearchDisplayDelegate and use something similar to:

[UIView beginAnimations:nil context:NULL];

CGRect headerViewFrame = self.headerView.frame;
headerViewFrame.origin.y -= 44.0f;
self.headerView.frame = headerViewFrame;

CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.origin.y -= 44.0f;
self.tableView.frame = tableViewFrame;

[UIView commitAnimations];

and

[UIView beginAnimations:nil context:NULL];

CGRect headerViewFrame = self.headerView.frame;
headerViewFrame.origin.y += 44.0f;
self.headerView.frame = headerViewFrame;

CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.origin.y += 44.0f;
self.tableView.frame = tableViewFrame;

[UIView commitAnimations];

... accordingly.

Upvotes: 8

Related Questions