I have story board setup with all view controller extending navigation controller with class NavigationController: UINavigationController, UIViewControllerTransitioningDelegate
with custom navigation bar setup for navigation controller with class CustomNavigationBar:UINavigationBar
Here is the code for NavigationController
class NavigationController: UINavigationController, UIViewControllerTransitioningDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Here is the code for CustomNavigationBar
class CustomNavigationBar: UINavigationBar {
override func awakeFromNib() {
var font = UIFont(name: "Montserrat-Light", size: 17)!
if "ar" == userLocale() {
font = UIFont(name: "DroidSansArabic", size: 17)!
}
let attribtutes = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: UIColor.black,
NSKernAttributeName: 5.0
] as [String : Any]
UINavigationBar.appearance().titleTextAttributes = attribtutes
UINavigationBar.appearance().tintColor = UIColor.black
UINavigationBar.appearance().backgroundColor = UIColor.white
let image = UIImage(named: "back-btn")
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -66), for: .default)
UINavigationBar.appearance().backIndicatorImage = image
}
}
So far so good, I now want to add a right bar navigation item with a custom view. I tried adding the following code in NavigationController::viewDidLoad()
let customView:UIView = UIView()
customView.backgroundColor = .green
customView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let item = UIBarButtonItem(customView: customView)
self.navigationItem.setRightBarButton(item, animated: false)
This for some reason is not showing up in navigation menu. Where am I going wrong?
You need add your custom navigation button code part in your base view controller, because every viewController have it own navigationItem
, that is why your custom button is not showed
You need use a BaseViewController
class for your needs, then subclassing all your viewController from your BaseViewController you only need add your navigation button customization code once, in viewDidLoad
Something like this
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let customView:UIView = UIView()
customView.backgroundColor = .green
customView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let item = UIBarButtonItem(customView: customView)
self.navigationItem.setRightBarButton(item, animated: false)
}
}