0

如何讓子視圖控制器修改導航控制器?如何讓子視圖控制器將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.navigationControllerviewDidLoad爲零,但不是在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魔術發生了

+0

呃erwald,我面臨與你一樣的情況。你能找到解決方案嗎? –

回答

0

可以使用

self.parentViewController.navigationController 

從容器視圖中獲得參考導航控制器?

+0

你的意思是從包含的視圖內嗎? 我其實不需要引用它。我認爲應該在添加搜索顯示控制器時「自動」完成,否?我將用我在那裏使用的一些代碼編輯我的答案。 – erwald

0

這可能會幫助您找到答案。我們用它來設定我們的導航控制器

[email protected]"Name of view goes here"; 

的標題,您應該能夠使用self.navigationItem獲得的句柄導航欄。

相關問題