导航栏的右键丢失

时间:2018-11-03 09:56:28

标签: ios iphone swift xcode

我正在尝试为导航栏的右键创建自定义按钮。但是它总是不见了。这是我从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
}

2 个答案:

答案 0 :(得分:1)

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

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)

尝试一下,让我知道它是否有效。希望对您有帮助。

答案 1 :(得分:1)

尝试使用以下方法添加右键按钮项:-

func configureRightBarButton(title: String, icon: UIImage?, withColor: UIColor?, withTarget: AnyObject) {
        // create back button
        let btnRightMenu: UIButton = UIButton()
        btnRightMenu.tintColor = withColor
        if var image = icon {
            image = image.withRenderingMode(.alwaysTemplate)
            btnRightMenu.setImage(image, for: .normal)
        }
        btnRightMenu.setTitle(title, for: .normal)
        btnRightMenu.setTitleColor(withColor, for: .normal)
        btnRightMenu.sizeToFit()
        btnRightMenu.addTarget(withTarget, action: #selector (rightBarButtonClick(sender:)), for: .touchUpInside)
        let barButton = UIBarButtonItem(customView: btnRightMenu)
        self.navigationItem.rightBarButtonItem = barButton
    }