Clinemi
Clinemi

Reputation: 926

UISearchBar not in the TableViewController's table view header?

I want to find out how to add a UISearchBar to a TableViewController - but not to the table view header.

I am having trouble with my existing search bar disappearing after scrolling in certain scenarios. I have found ways to make the search bar "float", but in a couple of corner cases the search bar still disappears after scrolling.

After googling this issue I have found that some people have taken the search bar out of the table view header to deal with this issue. That is relatively easy if your table view is added to a UIViewController. But how do you add a new view (in this case a search bar) to a TableViewController - that is not a subview of the table view automatically provided by the TableViewController?

iPad app iOS 6

-Thanks Mike C.

Upvotes: 1

Views: 609

Answers (2)

jesalerno
jesalerno

Reputation: 11

First, use storyboards. Add a UIView object to the table header. Then, put your UISearchBar in the UIView. Also, you will need to make your table view controller the delegate for your search bar. Instead of using the scrollViewDidScroll method (or similar), put your floating code into viewDidLayoutSubviews. This works in all cases. I also call bringToFront because I use a custom section header and need to make sure the table header view always stays on top. The top UIEdgeInset is the height of the tableHeaderView.

viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGRect frame=self.tableView.tableHeaderView.frame;
    frame.origin.y=self.tableView.contentOffset.y;
    if (frame.origin.y <= 0) {
        frame.origin.y=0;
        [self.tableView setContentInset:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
    } else {
        [self.tableView setContentInset:UIEdgeInsetsMake(48.0, 0.0, 0.0, 0.0)];
    }
    [self.tableView.tableHeaderView setFrame:frame];
    [self.tableView bringSubviewToFront:self.tableView.tableHeaderView];
}

Upvotes: 1

Clinemi
Clinemi

Reputation: 926

Since nobody from either Stackoverflow, or the Apple Developer's forums responded, I got help from Ron Adams in the Idaho branch of Cocoaheads. Basically, I ended up changing my UITableViewController to a UIViewController and manually adding the tableview and search bar. A little extra work, but it works great!

Upvotes: 0

Related Questions