ios - 从 UIPageViewContoller 中包含的 View 设置 UINavigationBar 标题

标签 ios objective-c uinavigationbar uipageviewcontroller

这是我遇到的问题。我无法为 UIPageViewController 中包含的 View 设置 UINavigationBar 标题。

应用程序的基本架构如下。

  1. 该应用的 Root View Controller 是一个 UITabBarController,其中包含 5 个导航 Controller 。

  2. 我遇到问题的第一个导航 Controller 包含一个页面 View Controller ,而这个页面 View Controller 包含许多 UIViewController。

  3. 我希望,当我滑动浏览每个 View Controller 时,我可以在 UINavigationBar 中设置标题。

我尝试了以下方法:

  1. 在页面 View Controller 中包含的 UIViewController 中,我尝试了 [self setTitle:@"Title I want"] - 它没有用。

    <
  2. 在同一个 UIViewController 中,我也尝试过 [self.navigationBar.navigationItem setTitle:@"Title I want"] - 这也没有用。

    <

我还尝试为 View Controller 设置标题,并尝试将其提取到 PageViewControllers 委托(delegate)方法 transitionCompleted 中,但这也没有用。

我想知道我是否应该回到绘图板,以及我是否正在使用这个 View 布局架构走入兔子洞。有没有其他人遇到过这个问题?如果遇到过,您是如何解决的?

编辑:我还必须补充一点,我正在以编程方式执行此操作。

感谢您的帮助。

最佳答案

所以,最后我想出了一种方法来实现这一点,虽然这不是我想要的最干净的解决方案,但仍然适合这个目的。

  1. 我创建了一个名为 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;
}
  1. 这些可以在添加到 UIPageViewController 之前像这样初始化。

代码示例

ChildViewController *aChildViewController = [[ChildViewController alloc] initWithIndex:1 andTitle:@"A Title"];
  1. 您需要将 UIPageViewControllerDelegate 添加到页面 View Controller 的界面。这样您就可以在 View 转换完成时实现委托(delegate)方法的代码,并且您需要设置标题。

  2. 当 UIPageViewController 加载时,我获取第一个 View Controller 并获取它的标题,将其设置为 UINavigationController 导航栏

代码示例

PageLeafViewController *initialViewController = (PageLeafViewController *)[self viewControllerAtIndex:0];
[self.navigationItem setTitle:initialViewController.navBarTitle];
  1. 当转换发生时,当转换到 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/

相关文章:

ios - 在 iOS6 中使用 Storyboard 子类化 UITabBarController

iphone - 在后台和 Nstimer 中工作时出现问题?

iphone - 发送到问题的无法识别的选择器

uinavigationbar - iOS7在UINavigationBar中添加UIsearchbar时未显示“取消”按钮

ios - 使用 initWithContentsOfURL 使用 iPod 歌曲 URL 初始化 AVAudioPlayer

ios - Swift 4 中 textField 的前 4 个字符的子字符串

ios - 将方法从我的自定义单元格类传递到主类

ios - 从 HTML 正文创建 PDF 文件并作为邮件附件发送,iOS

ios - 如何在导航栏右侧添加多个 UIBarButtonItems?

dart - Flutter:将键盘聚焦在后退导航上