Locking a UISearchBar to the top of a UITableView like Game Center

后端 未结 7 2077
梦毁少年i
梦毁少年i 2020-12-02 06:33

There\'s this cool feature in the UITableViews in Game Center and the search bars they have at their tops. Unlike apps where the search bar is placed in the table header vie

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 06:34

    All of the other answers here provided me with helpful information, but none of them worked using iOS 7.1. Here's a simplified version of what worked for me:

    MyViewController.h:

    @interface MyViewController : UIViewController  {
    }
    @end
    

    MyViewController.m:

    @implementation MyViewController {
    
        UITableView *tableView;
        UISearchDisplayController *searchDisplayController;
        BOOL isSearching;
    }
    
    -(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;
    }
    
    @end
    

    Note: If you're using "pull down to refresh" on your list, you'll need to replace scrollView.contentInset.top in scrollViewDidScroll: with a constant to allow the search bar to scroll over the refresh animation.

提交回复
热议问题