【问题标题】:Can't set UINavigationBar Title or place UIButtons in the UINavigationBar when back button is present当后退按钮存在时,无法设置 UINavigationBar 标题或将 UIButtons 放置在 UINavigationBar 中
【发布时间】:2019-05-11 22:12:43
【问题描述】:

我正在开发一个包含多个嵌套 UIViewController 的应用程序。我有两个视图,一个是带有 uibarbuttonitem 的根视图控制器,它连接到另一个 UIViewController。

被设置为不接受的 UIViewController 和 UIButtons 或 UIBarButtonItems,我似乎无法为其设置标题。

我需要在 UINavigationBar 中放置一个标题和其他 UIElements 但似乎没有任何效果,我在网上没有找到任何解决方案。

UINavigationBar 甚至没有出现在视图的层次结构中。

感谢您的合作。

【问题讨论】:

  • @vacawama 我已经编辑了帖子。请再次检查。
  • 尝试先添加一个 UINavigationItem。
  • 到目前为止你做了什么?你能告诉我们一些代码吗?
  • 在视图控制器中设置self.title = "whatever" in viewDidLoad 以设置标题。设置右栏按钮,如下所示:self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Foo", style: .plain, target: self, action: #selector(handleRightBarButton))

标签: swift uibutton uinavigationbar uibarbuttonitem


【解决方案1】:

你是对的。在 NavigationController 堆栈中的 ViewControllers 的情况下,Storyboard 布局不一致且令人困惑。第一个提供对 NavigationItem 的直接访问,但后面的不提供。我想那是因为只有一个 NavigationItem,它需要在 ViewController 被推送和弹出时动态更新。

解决这个问题的方法是在代码中完成。当一个 ViewController 被推送时,它的title 属性用于设置导航栏的标题。因此,在 NavigationController 堆栈中的每个 ViewController 中,将其 title 设置为 viewDidLoad

self.title = "titleForThisVC"

对于rightBarButton,您也可以通过编程方式添加它。如果这是您的 @IBAction 按钮:

@objc func handleRightBarButton() {
    print("right button")
}

然后你会像这样添加按钮(同样在viewDidLoad):

self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Foo", style: .plain,
     target: self, action: #selector(handleRightBarButton))

UITabBarControllers 最后一个陷阱

如果您的 NavigationControllers 是 UITabBarController 的子项,则标签栏中使用的标题将从代码设置的堆栈中的第一个 ViewController 中获取标题,但仅在该标签具有第一个被访问。为了解决这个问题,还应该在 Interface Builder

Attributes Inspector 中为顶级 ViewController 设置 title 属性

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 2023-04-01
    • 2011-12-24
    • 2011-01-12
    相关资源
    最近更新 更多