search视图总是显示在桌面上

我拿了一个UITableViewController,并试图在其中添加UISearchDisplayController。 我从互联网阅读了很多代码,但不知道我的错在哪里。

我的问题是为什么UISearchDisplayController不要总是坚持在UITableView之上。

这是我的代码

SearchView_controller.h @interface SearchView_controller : UITableViewController<UISearchBarDelegate,UISearchDisplayDelegate> @end SearchView_controller.m @interface SearchView_controller () { UISearchDisplayController *searchController; } @end @implementation SearchView_controller - (void)viewDidLoad { [super viewDidLoad]; self.title=@"Test"; UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, self.tableView.frame.origin.y, self.tableView.frame.size.width, 44)]; [searchBar sizeToFit]; [searchBar setDelegate:self]; searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self]; [searchController setSearchResultsDataSource:self]; [searchController setSearchResultsDelegate:self]; [searchController setDelegate:self]; [self.tableView setTableHeaderView:searchController.searchBar]; } -(void) scrollViewDidScroll:(UIScrollView *)scrollView { UISearchBar *searchBar = searchController.searchBar; CGRect rect = searchBar.frame; rect.origin.y = MAX(0, scrollView.contentOffset.y); searchBar.frame = rect; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 30; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"searchview_customecell"; searchview_customecell *cell = (searchview_customecell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; cell.lbl_name.text=@"test"; return cell; } searchview_customecell.h @interface searchview_customecell : UITableViewCell @property(nonatomic, weak) IBOutlet UILabel *lbl_name; @end searchview_customecell.m @implementation searchview_customecell - (void)awakeFromNib { // Initialization code } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // Configure the view for the selected state } @end 

最好处理UIViewController而不是UITableviewController来处理这些东西。

UITableViewController情况下,视图是tableView所以无论何时searchBar被添加它被添加到tableView

有两个可能的解决scheme来解决这个问题:

  1. 要么用UIViewControllerreplaceTableviewcontroller,并将search栏放在视图的开始处(不要将其添加到tableview标题中),然后是tableview。

  2. 跟随这个链接: 与UITableViewController的UISearchDisplayController