存在后退按钮时无法设置 UINavigationBar 标题或将 UIButtons 放置在 UINavigationBar 中

Can't set UINavigationBar Title or place UIButtons in the UINavigationBar when back button is present

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

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

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

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

感谢合作

你是对的。在 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))

gotcha UITabBarControllers

如果您的 NavigationControllers 是 UITabBarController 的 children,则标签栏中使用的标题将从堆栈中的第一个 ViewController 中选取标题作为由代码设置,但仅在首次访问该选项卡之后。为了解决这个问题,title 属性 也应该在 属性检查器 中的顶部 ViewController 中设置 界面建设者