Alex Petev
Alex Petev

Reputation: 489

RightBarButtonItem not showing up, when leftBarButtonItem works fine

In my app I have a push segue from HomeViewController to EditProfileViewController which should have a back button as a leftBarItem and a settings cog as a rightBarItem. The back button displays normally, but the right item is missing. These ViewControllers live happen in the MainNavigationController which has a Navigation Bar.

I tried to define the rightBarButton in ViewDidLoad of the EditProfileVC, I also tried to have a rightBarItem in the storyboard for the View controller.


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

Interestingly if I change the rightBar to a leftBar item, the back button is replaced with the settings cog and works as I expect, but I can't go back to the main page.


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

Upvotes: 3

Views: 2570

Answers (1)

PGDev
PGDev

Reputation: 24341

To set a rightBarButtonItem in a 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")
    }
}

In the above code I've added a UIBarButtonItem with title Settings as a rightBarButtonItem of navigationBar.

No need to configure leftBarButtonItem it not required. Back button is added by default.

Screenshot:

enter image description here

In case it doesn't satisfy your requirement, add a screenshot of what is expected so I can help.

Upvotes: 4

Related Questions