views:

162

answers:

2

Hi fellas,

I'm in the midst of an iPhone app that needs to have 4 separate UITableView objects sharing access to one UISearchBar in the first section and first row of the aforementioned UITableView objects.

I have tried to offset the UITableView's frame by 44 pixels, then adding the search bar as a subview of my UIViewController's view. That works, but I cannot use the table index to scroll up to the search bar, since it is not a cell in the tableview. I need to have the search bar in the table view itself.

My goal is to have the same UISearchBar in the first section of multiple tableviews.

Thanks so much.

+1  A: 

You could simply add the UISearchBar as the header view of each tableView as you switch between them.

[oldTableView setTableHeaderView:nil];
[newTableView setTableHeaderView:searchBar];

Of course, it's entirely possible that I've misunderstood what you're trying to do. If that's the case, please elaborate.

glorifiedHacker
+1  A: 

As already mentioned, you might want to put the search bar in the tableHeaderView property of UITableView, which will put it at the top of the table without having to do the manual positioning. I'm not sure how this works with indexing, though.

As for sharing a UISearchBar, I can't think of a good reason to instead of having one for each table view--the memory difference should be negligible, and setting and unsetting the delegate and whatnot could be a serious hassle. Was there a particular reason you wanted to share the search bar? If you want persistence, you can save the search bar text in viewWillDisappear and set it in viewWillAppear.

If you really want to put the search bar in the first cell, rather than the table header, you could do something like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = //etc, normal cell creation

    if (indexPath.section == 0 && indexPath.row == 0) {
        [cell addSubview:self.searchBar];
    }
    return cell;
}

But putting a search bar in a table header is much more common, and much easier to manage.

eman