I have tried many solutions but it’s not working as expected
As per my application structure in every viewcontoller viewWillDisappear we have to restore navigation bar like below code
let textAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
navigationController?.navigationBar.tintColor = .blue
navigationController?.navigationBar.backgroundColor = .white
navigationController?.navigationBar.isTranslucent = false
// Restore the navigation bar to default from transparent
if #available(iOS 15, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.backgroundColor = .white
appearance.titleTextAttributes = textAttributes
// Customizing our navigation bar
navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
} else {
navigationController?.navigationBar.titleTextAttributes = textAttributes
navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
navigationController?.navigationBar.shadowImage = nil
}
and in other viewcontroller i need to add leftBarButtonItem and rightBarButtonItem with different colors but it always comes blue only when i change above code navigationBar.tinitColor i can able to see the color changes in navigationItem barbutton but both are same color which is what i give in navigationBar.tinitColor
this is rightBarButtonItem tint color change code
let barButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
barButtonItem.tintColor = .black
barButtonItem.accessibilityIdentifier = "navbar_notificationbutton"
navigationItem.rightBarButtonItem = barButtonItem
Actual Result screenshot
Expected Result screenshot
Thanks in Advance!!!
CodePudding user response:
To change or apply different tint color for the navigation bar buttons you can use the below code
let backButton = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0))
backButton.setImage(UIImage(systemName: "chevron.backward"), for: .normal)
backButton.addTarget(self, action: #selector(btnBack), for: .touchUpInside)
backButton.tintColor = .red
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
let notificationButton = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0))
notificationButton.setImage(UIImage(systemName: "bell"), for: .normal)
notificationButton.addTarget(self, action: #selector(btnShowNotifications), for: .touchUpInside)
notificationButton.tintColor = .systemGreen
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: notificationButton)
In the above code, I created a back
button and assigned it to leftBarButtonItem
, and similarly, I created another button with different tint color and assigned it to rightBarButtonItem
.