当leftBarButtonItem运行正常时,RightBarButtonItem未显示

时间:2019-05-21 11:48:12

标签: ios swift xcode uinavigationbar

在我的应用中,我有一个从HomeViewControllerEditProfileViewController的推送服务,其中应该有一个后退按钮为leftBarItem和一个设置齿轮为rightBarItem。后退按钮正常显示,但右边的项目丢失。这些ViewControllers实时发生在具有导航栏的MainNavigationController中。

我尝试在rightBarButton的{​​{1}}中定义ViewDidLoad,也尝试在故事板中为View控制器添加一个EditProfileVC

rightBarItem

有趣的是,如果我将rightBar更改为leftBar项目,则后退按钮将替换为设置cog,并且可以按我期望的方式工作,但是我无法返回主页。


    let buttonItem = UIBarButtonItem(image: settingsIcon, style: .plain, target: self, action: #selector(settingsPressed))
    buttonItem.tintColor = UIColor(.settingsIconTint)
    navigationItem.rightBarButtonItem = buttonItem

1 个答案:

答案 0 :(得分:1)

要在rightBarButtonItem中设置navigationBar

class HomeViewController: UIViewController {
    @IBAction func openEditVC(_ sender: UIButton) {
        if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "EditProfileViewController") as? EditProfileViewController {
        self.navigationController?.pushViewController(controller, animated: true)
        }
    }
}

class EditProfileViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let buttonItem = UIBarButtonItem(title: "Settings", style: .plain, target: self, action:  #selector(settingsPressed))
        buttonItem.tintColor = .red
        navigationItem.rightBarButtonItem = buttonItem
    }

    @objc func settingsPressed() {
        print("Setting Pressed")
    }
}

在上面的代码中,我添加了UIBarButtonItemtitle作为Settings的{​​{1}}的{​​{1}}。

不需要配置rightBarButtonItem,这不是必需的。默认添加navigationBar

截屏:

enter image description here

如果它不能满足您的要求,请添加期望的屏幕截图,以便我提供帮助。