显示结果后关闭UISearchBar

时间:2014-02-14 05:33:17

标签: ios iphone objective-c uitableview uisearchbar

UITableView我有一个隐藏的UISearchBar作为应用启动时的默认行为。稍后,如果用户需要搜索字词,则UIButton操作会显示UISearchBar和键盘。 我遇到的问题是,在执行搜索后,我不知道如何取消搜索或关闭UISearchBar。如果用户点击键盘搜索按钮,键盘就会消失,即可,但如果用户点击UISearchBar取消按钮,则会发生任何事情。

这是我隐藏UISearchBar

的代码
- (void)hideSearchBar {

    CGRect newBounds = self.tableView.bounds;
    if (self.tableView.bounds.origin.y < 44) {
        newBounds.origin.y = newBounds.origin.y + self.searchBar.bounds.size.height;
        self.tableView.bounds = newBounds;

    }
}

这是我的代码,用于显示UISearchBar和键盘:

- (IBAction)showSearchBar:(id)sender {


    [self.searchBar becomeFirstResponder];
}

2 个答案:

答案 0 :(得分:1)

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar

以上是UISearchBar的委托方法,当您按下取消按钮时,它用于管理UISearchBar

根据您的要求提供代码。

如此

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @""; // clear text of search
    [searchBar resignFirstResponder]; // keyBoard is hide
    [self.searchBar setShowsCancelButton:NO animated:YES]; // remove cancel button from searchBar
   // Etc..
}

已编辑:

您可以声明并访问UISearchBar,例如

@interface myViewController : UIViewController <UISearchBarDelegate, UISearchBarDelegate> // add delegate and datasource to .h file

@property (nonatomic, strong) UISearchBar *searchBar;

.m UISearchBar

的文件创建
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f,38.0f,320.0f,0.0f)]; // set frame as you want.
[self.searchBar sizeToFit];
self.searchBar.delegate = self;
self.searchBar.tintColor = [UIColor colorWithRed:(93/255.f) green:(156/255.f) blue:(13/255.f) alpha:1.0f]; // set color as you want.
[self.view addSubview:self.searchBar];

答案 1 :(得分:1)

试试这个,

使用searchBarCancelButtonClicked:的{​​{1}}委托方法并致电UISearchBar

hideSearchBar

添加

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { 

    [searchBar setText:@""];
    [searchBar resignFirstResponder];
    [self hideSearchBar];
}