iOS修复UITableViewController顶部的搜索栏?

Bha*_*rat 8 objective-c uisearchbar ios

我在表头上添加搜索栏并将其浮动在scrollViewDidScroll方法中,但是当我滚动时没有点击搜索栏(即我转到视图并滚动),然后搜索栏不会保持在顶部但它向上滚动表然而,一旦我点击搜索栏并点击搜索栏上的取消按钮,然后如果我滚动表格,搜索栏将保持在顶部.我的代码是 -

-(void)viewDidLoad {
    [super viewDidLoad];

    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    searchBar.delegate = self;

    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    searchDisplayController.delegate = self;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;

    UIView *tableHeaderView = [[UIView alloc] initWithFrame:searchDisplayController.searchBar.frame];
    [tableHeaderView addSubview:searchDisplayController.searchBar];
    [tableView setTableHeaderView:tableHeaderView];

    isSearching = NO;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {

    UISearchBar *searchBar = searchDisplayController.searchBar;
    CGRect searchBarFrame = searchBar.frame;

    if (isSearching) {
        searchBarFrame.origin.y = 0;
    } else {
        searchBarFrame.origin.y = MAX(0, scrollView.contentOffset.y + scrollView.contentInset.top);
    }

    searchDisplayController.searchBar.frame = searchBarFrame;
}

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
    isSearching = YES;
}

-(void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller {
    isSearching = NO;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我正在使用UITableViewController子类,并且不想将其更改为UIViewController.任何帮助,将不胜感激.

编辑:我也在这里使用节头UITableViewController,在其他UITableViewController没有节头,这个代码工作正常.这是一个问题与节头和表头一起?

Ben*_*min 16

您的搜索栏滚动表内容的原因是您已将其直接放在表中,从而使其成为表的子标题部分.那部分总是滚动...

以下是如何实现这一目标的.它实际上非常简单.(以下示例依赖于Storyboard,但无论您使用什么,机制都是相同的):

1)使用的UIViewControllerNOT一个的UITableViewController

2)添加的UITableView孩子的的父母 的UIView

3)添加UISearchBarController也为孩子的视UIView的,还不如UITableView中的孩子(的UITableView和UISearchController是兄弟)

你应该有以下布局:

在此输入图像描述

编辑:要记住的重要事情是把UISearchBarController 高于同级的UITableView.否则,你可能会看到的UITableView 重叠UISearchBarController当后者侧重.

编辑2:顺便说一句,如果您使用AutoLayout,请记住设置tableView相对于SearchBar的TOP约束...

运行它并欣赏结果.

希望这可以帮助.