当用户触摸UIBarButtonItem时,在tableView上显示UISearchBar

时间:2013-10-31 13:55:03

标签: ios objective-c uitableview uisearchbar uisearchdisplaycontroller

在我的iOS应用中,我希望在UINavigationController中设置右侧搜索按钮,当用户触摸该按钮时,会显示UISearchBar上方的UITableView

我想在加载视图时隐藏UISearchBar,然后在用户点击UISearchDisplayController中的取消按钮时再次隐藏。

我到处搜索,找不到一个例子。帮助

1 个答案:

答案 0 :(得分:1)

有一个很好的示例项目here。关键点是:

1.在显示视图之前隐藏搜索栏:

-(void)viewWillAppear:(BOOL)animated {
    [self hideSearchBar];        
}

-(void)hideSearchBar {
   CGRect newBounds = self.tableView.bounds;
   newBounds.origin.y = newBounds.origin.y + self.searchBar.bounds.size.height;
   self.tableView.bounds = newBounds;
}

2.在搜索按钮的操作目标上,显示搜索栏

 // make the search bar visible
 // code example from https://github.com/versluis/Table-Seach-2013 to deal with iOS 7 behavior

-(IBAction)displaySearchBar:(id)sender {

    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

    NSTimeInterval delay;
    if (self.tableView.contentOffset.y >1000) delay = 0.4;
    else delay = 0.1;
    [self performSelector:@selector(activateSearch) withObject:nil afterDelay:delay];

}

- (void)activateSearch
{
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    [self.searchBar becomeFirstResponder];

}

3.最后,单击“取消”时隐藏SearchBar

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self hideSearchBar];
}