iosswiftuikituibarbuttonitemuinavigationitem

Changing background colour of navigationItem and barButtonItem in iOS 16.2


I just need to change the background colour of navigationItem and barButtonItem in my app.

I have tried so many methods in stack overflow but none of them worked.
I have also tried in my storyboard by using UserDefinedRunTimeAttributes by giving key path as background colour but that also didn't work.enter image description here

I need an background colour for this navigationItem and their you can see an save UIBarButtonItem, also I need on that a background colour and to be bended with some corner radius.


Solution

  • You've to create your custom view and add your modified button in the custom view and add the custom view in the UIBarButtonItem. That worked for me totally!

                let button = UIButton(type: .system)
                button.frame = customView.bounds
                button.setTitle("Logout", for: .normal)
                button.setTitleColor(.white, for: .normal)
                button.backgroundColor = .blue
                button.layer.cornerRadius = 12
                // Add the UIButton to the custom view
                customView.addSubview(button)
    
                // Create a UIBarButtonItem with the custom view
                let barButtonItem = UIBarButtonItem(customView: customView)
                let logoutBarButtonItem = UIBarButtonItem(customView: customView)
                self.navigationItem.rightBarButtonItem  = logoutBarButtonItem
    

    enter image description here