首页 > 解决方案 > 导航栏的右键不见了

问题描述

我正在尝试为导航栏的右键创建一个自定义按钮。但它总是失踪。这是我的代码,它是从以下位置调用的viewWillAppear:

func setNavBar() {
    self.navigationController?.setNavigationBarHidden(false, animated: false)

    let rightNavButton : UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "photo_camera"), style: .plain, target: self, action: #selector(onCameraButton(sender:)))

    self.navigationController?.navigationBar.topItem?.hidesBackButton = false
    self.navigationController?.navigationBar.topItem?.rightBarButtonItem = rightNavButton

}

显示了后退按钮,因此topItem绝对不是零。但我不知道为什么,但右边的栏按钮不见了。我试过把它变成一个只有一个项目的数组,但它仍然没有用。有人可以帮我吗?谢谢。

编辑:顺便说一句,具有此代码的视图控制器是从另一个具有非常相似代码的视图控制器调用的,并且它运行良好。不知道这两者有什么区别。这是工作代码:

func setNavBar() {
    self.navigationController?.setNavigationBarHidden(false, animated: false)

    let rightNavButtons : [UIBarButtonItem] = [
        UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(onEditButton)),
        UIBarButtonItem(image: UIImage(named: "settings"), style: .plain, target: self, action: #selector(onSettingsButton))

    ]

    self.parent?.title = "Profile"
    self.navigationController?.navigationBar.topItem?.hidesBackButton = true
    self.navigationController?.navigationBar.topItem?.rightBarButtonItems = rightNavButtons
}

标签: iosiphoneswiftxcode

解决方案


我在当前项目中实现了以下代码来添加右栏按钮。

func addRightButton(title: String) {
    let barRightButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(rightBarButtonTapped(sender:)))
    self.navigationItem.rightBarButtonItem = barRightButton
}

在我的整个项目中,这对我来说效果很好。你应该需要使用self.navigationItem.rightBarButtonItem而不是self.navigationController?.navigationBar.topItem?.setRightBarButton(rightNavButton, animated: false)

试试这个,让我知道它是否有效。我希望这能帮到您。


推荐阅读