【问题标题】:UINavigationBar not displaying title in iOSUINavigationBar 在 iOS 中不显示标题
【发布时间】:2014-06-19 05:13:18
【问题描述】:

尝试以编程方式设置 NavBar,但我的标题未显示在导航栏中。关于发生了什么的任何想法?

UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
navbar.topItem.title = @"My accounts";

[self.view addSubview:navbar];

【问题讨论】:

    标签: ios objective-c uinavigationbar


    【解决方案1】:

    这里的问题是你对UINavigationBar的使用。

    阅读UINavigationController programming here.的文档

    您不应创建自己的 UINavigationBar 并将其作为子视图添加到视图控制器的视图中。

    正确的做法是创建一个UINavigationController 并将您的视图控制器添加到它的堆栈中。

    所以是这样的:

    CustomViewController *myViewController = ...// whatever initialization you do
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myViewController];
    

    每个视图控制器都有自己的UINavigationItem,当视图控制器位于堆栈顶部时,导航控制器使用它来设置导航栏的视图。

    所以在您的CustomViewController.m 中,可能在init 方法或viewDidLoad 中,

    您可以通过执行以下操作来设置导航项:

    self.navigationItem.title = @"whatever";
    self.navigationItem.rightBarButtonItem = ...// create a UIBarButtonItem and set it here if you want a button on the right side of the navigation bar
    

    再一次,您不要直接触摸导航栏或将其添加到您的视图层次结构中。 UINavigationController 为您处理所有这些。

    【讨论】:

      【解决方案2】:

      使用

      self.navigationItem.title = @"the title";
      

      因为设置 navBar.topItem.title 并非在所有情况下都有效。

      【讨论】:

      • 不幸的是什么也没做。
      • 你在使用 UITabbarController 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多