如何从navigationItem添加和删除searchBar

时间:2018-11-03 08:21:02

标签: ios objective-c uinavigationcontroller

我在将UISearchControllers searchBar添加和删除到UINavigationBar时遇到麻烦。

这是我在做什么:

将searchBar添加到视图中

searchController = [[UISearchController alloc]initWithSearchResultsController:nil];

searchController.searchResultsUpdater = self;
searchController.searchBar.delegate = self;

searchController.dimsBackgroundDuringPresentation = NO;
searchController.hidesNavigationBarDuringPresentation = NO;
searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
searchController.searchBar.barTintColor = [UIColor blackColor];
searchController.searchBar.tintColor = [UIColor darkGrayColor];

[searchController.searchBar setFrame:CGRectMake(0, 200, 320, searchController.searchBar.frame.size.height)];
[self.view addSubview:searchController.searchBar];

在按钮上,单击将searchBar添加到navigationItem 这样可以正常工作

[self.navigationController setNavigationBarHidden:false];
self.navigationItem.titleView = searchController.searchBar;
self.navigationItem.hidesBackButton = true;

这是我得到奇怪行为的地方:

在另一个按钮上,单击从导航栏中删除searchBar并将其重新添加到视图中

[searchController.searchBar removeFromSuperview];
[self.navigationController setNavigationBarHidden:YES animated:true];
[self.view addSubview:searchController.searchBar];

[searchController.searchBar setFrame:CGRectMake(0, 200, 320, searchController.searchBar.frame.size.height)];

searchBar已按预期方式从导航栏中删除,但不会返回到主视图。 (好吧,我在任何地方都看不到)

我记录了搜索栏的值,可以看到它具有我给定的框架。

这里的任何帮助将不胜感激,

谢谢

1 个答案:

答案 0 :(得分:0)

您应先将navigationItem .titleView设置为nil,然后在主线程中设置setFrame:

- (IBAction)addBar:(id)sender {
    self.navigationItem.titleView = nil;
    [searchController.searchBar removeFromSuperview];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationItem.titleView = searchController.searchBar;
    self.navigationItem.hidesBackButton = YES;
}

- (IBAction)removeBar:(id)sender {
    self.navigationItem.titleView = nil;
    [searchController.searchBar removeFromSuperview];
    [self.view addSubview:searchController.searchBar];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self->searchController.searchBar setFrame:CGRectMake(0, 200, 320, self->searchController.searchBar.frame.size.height)];
    });
}

顺便说一句,我认为将搜索栏添加到UIView时最好将其放在包装器navigationItem.titleView中。