Locking a UISearchBar to the top of a UITableView

I want to get the behavior like this: I have a UISearchBar, which is a table header view of my tableview. When scrolling the table, the search bar does indeed move, but if you scroll above the boundaries of the table, the search bar never stops touching the navigation bar.

I found a good answer here - Locking a UISearchBar to the top of a UITableView like Game Center But it not works on iOS 6 - manipulations with table view header frame don't work

What can be the reason of this?


I found a solution, which works on iOS 6 and lower

Make a subclass of UITableView and override layoutSubviews method

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGRect rect = self.tableHeaderView.frame;
    rect.origin.y = MIN(0, self.contentOffset.y);
    self.tableHeaderView.frame = rect;
}

If you use the following:

[_tableView setTableHeaderView:_searchBar];

When you scroll the table view beyond the first row, the search bar should also disappear rather than sticking to the top of the view.

Without seeing your code, I can only assume that perhaps you have added the UISearchBar as your section header rather than the table header?


That because iOS6 sdk not update when scrolling, maybe same optimize. so need to call tableview layoutSubviews when scroll.

-(void)scrollViewDidScroll:(UIScrollView *)scrollView 
{
    UISearchBar *searchBar = searchDisplayController.searchBar;
    CGRect rect = searchBar.frame;
    rect.origin.y = MIN(0, scrollView.contentOffset.y);
    [scrollView layoutSubviews];
    searchBar.frame = rect;
}
链接地址: http://www.djcxy.com/p/55966.html

上一篇: 带有标题的UITableView对除UISearchBar以外的任何视图都不正确

下一篇: 将UISearchBar锁定到UITableView的顶部