【发布时间】:2015-06-24 09:59:32
【问题描述】:
如何让子视图控制器修改导航控制器?
我现在正面临这个问题,并且无法找到一个有效的解决方案,更不用说一个运作良好的解决方案了。
基本上,现在我有一个UINavigationController,其中包含一个UITableViewController,导航栏中有一个搜索栏。到目前为止一切顺利 - 一切正常。
但是,有时我想在导航栏和表格视图顶部之间显示一些自定义视图。为此,我认为最好创建另一个视图控制器(我们称之为ContainerViewController),它由导航控制器提供。这个容器视图控制器将表格视图控制器作为一个子视图,并且可以插入它希望插入的任何自定义视图。视图控制器层次结构应如下所示:
UINavigationController
ContainerViewController
UITableViewController (with UISearchDisplayController)
现在我遇到了一个问题,因为UISearchDisplayController 的搜索栏应该显示在导航栏中(通过调用didSetupSearchDisplayController),但我显然希望与它有关的所有逻辑都保留在UITableViewController .我需要容器视图控制器在这里充当中间人。我试图解决这个问题,但还没有找到解决方案。
这是我实例化表格视图控制器并将其作为子视图控制器添加到容器视图控制器中的方法。
- (void)viewDidLoad {
[super viewDidLoad];
// Load view controller from storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
self.contentViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyListViewController"];
self.contentViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
// Add its view to the content view
[self addChildViewController:self.contentViewController];
[self.container addSubview:self.contentViewController.view];
[self.contentViewController didMoveToParentViewController:self];
// Set up constraints
[self.contentViewController.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
}
在子视图控制器中,我注意到self.navigationController 在viewDidLoad 中为零,但在didMoveToParentViewController 中不为零。所以以下工作:
- (void)didMoveToParentViewController:(UIViewController *)parent {
// Hide separator below navigation bar
self.navigationController.navigationBar.clipsToBounds = YES;
}
但我无法将搜索栏设置为在导航栏中显示,也无法在子视图控制器中设置导航栏标题(带有self.title = ...)。
不胜感激。
编辑:这是我在UITableViewController(包含的视图)中用于创建搜索显示控制器的一些代码:
UISearchBar *searchBar = [[UISearchBar alloc] init];
self.mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
// Show search bar in navigation bar (instead of in its own bar underneath)
self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
// Set self as delegate to search display controller and its table view
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDelegate = self;
我尝试在viewDidLoad(其中self.navigationController 为零)和didMoveToParentViewController(存在导航控制器)中执行此操作,但这似乎无关紧要。我的猜测是displaysSearchBarInNavigationBar 魔法发生在子视图被实例化之后但在它被添加为子视图之前(因此可以访问导航控制器)。
【问题讨论】:
-
嗨,erwald,我面临着和你一样的情况。你找到解决办法了吗?
-
@erwald 你有没有找到一种方法来完成这项工作?
标签: ios uinavigationcontroller uisearchbar uisearchdisplaycontroller