Iphone 如何显示搜索栏的取消按钮?

Iphone 如何显示搜索栏的取消按钮?,iphone,uinavigationbar,uisearchbar,Iphone,Uinavigationbar,Uisearchbar,当用户开始在搜索栏上编辑时,我想隐藏我页面的导航栏,我还想显示一个取消按钮。 已完成,但当我打开UISearchBar时,无法访问“取消”按钮 谢谢大家 - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { self.navigationController.navigationBar.hidden=TRUE; CGRect r=self.view.frame; r.origin.y=-44;

当用户开始在搜索栏上编辑时,我想隐藏我页面的导航栏,我还想显示一个取消按钮。
已完成,但当我打开UISearchBar时,无法访问“取消”按钮 谢谢大家

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    self.navigationController.navigationBar.hidden=TRUE;
    CGRect r=self.view.frame;
    r.origin.y=-44;
    r.size.height+=44;

    self.view.frame=r;

    searchBar.showsCancelButton=TRUE;

}

使用此代码显示
取消
按钮。当您在
搜索栏中输入文本时,它将显示按钮

-(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
}
目标C 敏捷的
您需要使用UISearchDisplayController,它将为您自动隐藏导航栏。 这是密码

-(void) createSearchBar
{
     _searchBar          = [[SearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
     _searchBar.delegate = self;
     [self.view addSubview:_searchBar];

    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    searchDisplayController.delegate = self;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    searchDisplayController.searchResultsTableView.sectionHeaderHeight = 10;
    searchDisplayController.searchResultsTableView.sectionFooterHeight = 0;
    [searchDisplayController.searchResultsTableView setSeparatorColor:[Color whiteColor]];  
}
您必须在.h文件中实现协议UISearchBarDelegate、UISearchDisplayDelegate、UITableViewDelegate、UITableViewDataSource


另外_searchBar和searchDisplayController是在.h文件中定义的变量。

使用此代码在
搜索栏中显示/隐藏取消按钮

当用户在搜索栏中开始编辑时,显示“取消”按钮

只有正确设置了
SearchBar
的委托,才能访问以下方法

 -(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar
  {
    //This'll Show The cancelButton with Animation  
    [searchBar setShowsCancelButton:YES animated:YES];
    //remaining Code'll go here
  }
当用户单击“取消”按钮时,隐藏“取消”按钮

 - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
 {
        //This'll Hide The cancelButton with Animation  
      [searchBar setShowsCancelButton:NO animated:YES];
       //remaining Code'll go here
 }
使用此代码

searchBar.showsCancelButton=YES;

Swift 4:

以下两行代码用于显示取消按钮:

searchBar.setShowsCancelButton(true, animated: true)
searchBar.showsCancelButton = true

searchbartextdibeginediting()方法中调用
将在单击搜索栏后显示取消按钮。

回答得不错!还有一件事我想知道。当TextBeginEdit时,我可以通过编程方式显示灰色覆盖吗?从iOS 8开始,您不应该再使用UISearchDisplayController。改用UISearchController。编辑时没有显示“取消”按钮的设置。。。很好的苹果小姐:\通过这个,你会得到更好的理解。。
searchBar.showsCancelButton=YES;
searchBar.setShowsCancelButton(true, animated: true)
searchBar.showsCancelButton = true