loganTheFighter
loganTheFighter

Reputation: 21

How to add a search bar at the bottom of a table view in Xcode?

I am developing an iOS application, and I want to add a search button that initiates a search of a table view. When searching, the search bar should not be scrolled with the table cells.

Upvotes: 1

Views: 1036

Answers (1)

jszumski
jszumski

Reputation: 7416

To make a search bar (or any view really) "stick" to the top or bottom of a UITableView there are two approaches:

  • Adjust the frame of the table to be the view height minus the height of your bar, and then set the bar's frame to {0, 0, CGRectGetWidth(self.tableView.frame), CGRectGetHeight(self.tableView.frame)}, which would position it statically at the bottom of the view. If you are using a stock UITableViewController, you'll need to do some additional work because self.view and self.tableView both point to the same object. You'll need to set a new UIView to self.view which will then be the container for the table view and your search bar view.

  • Add the bar as a subview of table, then implement UIScrollViewDelegate in your controller and use scrollViewDidScroll: (which fires whenever the user scrolls the view) to update the bar's position. The new position would be something like:

    CGRect adjustedFrame = self.searchBarView.frame;
    adjustedFrame.origin.y = self.tableView.contentOffset.y + CGRectGetHeight(self.tableView.frame) - CGRectGetHeight(self.searchBarView.frame);
    self.searchBarView.frame = adjustedFrame;
    

Upvotes: 2

Related Questions