Hiding the UISearchBar with animiation
I recently built an application where I wanted to be able to toggle the UISearchBar
that sits on top of the UITableView. Basically, the app would provide a magnifiying glasses button and when clicked, it would hide this view.
By default, the search bar would be showing.
The first step to this is to create a local BOOL
named _isHidden
and set it to NO
in viewDidLoad
.
Now, to make the UISearch bar disappear, you need to use a UIView animation block:
This code is pretty simple. First, I’m looking at the global _isHidden
variable and setting the frame of the UISearchBar
to either 0.0f
or searchBarHeight
(currently set to 44.0f
). In the animation block, I am reseting the frame over a period of 300 milliseconds. After the animation is complete, it is important that you reset the tableHeaderView, otherwise you are going to see a gap at the top of your UITableViewController
. To hide this gap, you set
And when you want to un-hide the UISearchBar
, use:
Notice, tableViewHeader
was set in viewDidLoad
. I can confirm this works pretty well, and I have not found a better solution online after searching for about 15 minutes.