如何讓子視圖控制器修改導航控制器?如何讓子視圖控制器將UISearchBar添加到父級的UINavigationController?
我現在面臨這個問題,一直沒有找到一個可行的解決方案,更不用說一個效果很好的解決方案。
基本上,現在我有一個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
是nil這樣做,並在didMoveToParentViewController
,其中存在的導航控制器,但它似乎並不重要。我的猜測是,在子視圖被實例化之後,但在它被添加爲子視圖(並因此可以訪問導航控制器)之前,displaysSearchBarInNavigationBar
魔術發生了。
呃erwald,我面臨與你一樣的情況。你能找到解決方案嗎? –