【问题标题】:How to add and remove searchBar from navigationItem如何从 navigationItem 添加和删除 searchBar
【发布时间】:2019-04-07 08:24:15
【问题描述】:

我在向 UINavigationBar 添加和删除 UISearchControllers searchBar 时遇到问题。

这是我正在做的事情:

将 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 已按预期从导航栏中移除,但并未返回到主视图。 (好吧,我在任何地方都看不到)

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

我们将不胜感激任何帮助,

谢谢

【问题讨论】:

    标签: ios objective-c uinavigationcontroller


    【解决方案1】:

    您应该首先将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)];
        });
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多