Sliding Search Bar Down and Simultaneously Resizing Sibling View
-
15-06-2021 - |
Question
I have a UIView
-- call it HomeView
that contains a UITableView
and a UISearchBar
. That is, they are subviews. These are added in viewDidLoad
for HomeView
. A picture is worth a thousand words:
As can be seen from these screenshots, the first item in the UITableView
is hidden once the UISearchBar
is displayed. Here is the relevant code:
- (void) viewDidLoad
self.table_view = [UITableView.alloc.initWithFrame: self.view.bounds style:UITableViewStylePlain];
self.table_view.bounds.origin.y += 44;
self.table_view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// ^^^ This is the code I believe is one source of my problem
// Triggered when search button in nav bar is pressed
// code to calculate delta here
// Here's how the view is animated. The search bar frame
// is dropped down (works), and ideally, the tableview
// drops down exactly the same amount at the same time.
// If the action is to hide, then the inverse happens
// because +delta+ will have been calculated as a
// negative number above.
[UIView animateWithDuration: 0.7
delay: 0.0
options: UIViewAnimationOptionCurveEaseIn
animations:^ {
self.searchBar.frame = CGRectOffset(@searchBar.frame, 0.0, delta);
}
completion:^(BOOL finished){
self.searchBarVisible = !self.searchBarVisible
self.searchBar.hidden = !self.searchBarVisible
edgeInsets = UIEdgeInsetsMake(0.0f, self.searchBarVisible ? delta : 0.0f, 0.0f, 0.0f)
[tableView setContentInset: edgeInsets]
}
];
What actually happens is that the search bar slides down as expected in response to the search button press and then slides up on next button press. However, the table view never adjusts.
The problem, as near as I can tell, is that in viewDidLoad
, the enclosing HomeView
has not been rendered, so the size is as-yet unknown. I can get the screen dimensions and use that, but I thought the auto resizing mask was better practice, right?
Are there obvious flaws in this, and is there a way to get the table view to animate down at the same time the search bar is?
Thanks
Solution
All right, let's try this again!
In your animation block, change the line where you make edgeInsets to:
edgeInsets = UIEdgeInsetsMake(self.searchBarVisible ? delta : 0.0f, 0.0f, 0.0f, 0.0f);
From what I can tell, the first argument is the top, and the one you had set was the left inset.