这是我遇到的问题。我无法为 UIPageViewController 中包含的 View 设置 UINavigationBar 标题。
应用程序的基本架构如下。
该应用的 Root View Controller 是一个 UITabBarController,其中包含 5 个导航 Controller 。
我遇到问题的第一个导航 Controller 包含一个页面 View Controller ,而这个页面 View Controller 包含许多 UIViewController。
我希望,当我滑动浏览每个 View Controller 时,我可以在 UINavigationBar 中设置标题。
我尝试了以下方法:
在页面 View Controller 中包含的 UIViewController 中,我尝试了
<[self setTitle:@"Title I want"]
- 它没有用。在同一个 UIViewController 中,我也尝试过
<[self.navigationBar.navigationItem setTitle:@"Title I want"]
- 这也没有用。
我还尝试为 View Controller 设置标题,并尝试将其提取到 PageViewControllers 委托(delegate)方法 transitionCompleted 中,但这也没有用。
我想知道我是否应该回到绘图板,以及我是否正在使用这个 View 布局架构走入兔子洞。有没有其他人遇到过这个问题?如果遇到过,您是如何解决的?
编辑:我还必须补充一点,我正在以编程方式执行此操作。
感谢您的帮助。
最佳答案
所以,最后我想出了一种方法来实现这一点,虽然这不是我想要的最干净的解决方案,但仍然适合这个目的。
- 我创建了一个名为 PageLeafViewController 的新类,并设置了它的 init 方法,如下所示。页面 View Controller 的 subview Controller 继承自此。这是代码。
代码示例
- (id)initWithIndex:(NSUInteger)index andTitle:(NSString *)navBarTitle; {
if(self = [super init]) {
self.index = index;
self.navBarTitle = navBarTitle;
}
return self;
}
- 这些可以在添加到 UIPageViewController 之前像这样初始化。
代码示例
ChildViewController *aChildViewController = [[ChildViewController alloc] initWithIndex:1 andTitle:@"A Title"];
您需要将 UIPageViewControllerDelegate 添加到页面 View Controller 的界面。这样您就可以在 View 转换完成时实现委托(delegate)方法的代码,并且您需要设置标题。
当 UIPageViewController 加载时,我获取第一个 View Controller 并获取它的标题,将其设置为 UINavigationController 导航栏
代码示例
PageLeafViewController *initialViewController = (PageLeafViewController *)[self viewControllerAtIndex:0];
[self.navigationItem setTitle:initialViewController.navBarTitle];
- 当转换发生时,当转换到 View 完成时,我们再次将标题设置为新 subview Controller 的标题。
代码示例
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {
PageLeafViewController *currentLeaf = (PageLeafViewController *)[self.pageViewController.viewControllers lastObject];
[self.navigationItem setTitle:currentLeaf.navBarTitle];
}
注意:当显示新的 subview Controller 时,会自动调用上面的方法。
虽然这不是目前最优雅的解决方案,但我认为不可能从 subview 中调用函数来更新 NavigationBar 标题,除非有人想纠正我?
希望这对您有所帮助。
关于ios - 从 UIPageViewContoller 中包含的 View 设置 UINavigationBar 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28771075/