Reputation: 748
I made a custom UINavigationBar and I would like to use it globally. I see in other examples that for setting UINavigationBar appearance globally, you have to do something like this let navigationBar = UINavigationBar.appearance()
in the AppDelegate. Then you can set up the the properties. In my case, I have set up all the properties in class var
like so:
extension UINavigationBar {
class var customNavBar : UINavigationBar{
let navigationBar = UINavigationBar()
navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Avenir-Black", size: 40)!, NSForegroundColorAttributeName: UIColor.RED]
//gets rid of black separation bar
navigationBar.shadowImage = UIImage()
navigationBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
//set the background color to white
navigationBar.tintColor = UIColor.white
navigationBar.isTranslucent = false
return navigationBar
}
}
Now, how can I set the UINavigationBar from AppDelegate to inherent these properties. I mean having something like this in the app delegate. Or similar of course. In AppDelegate:
let navigationBar = UINavigationBar.customNavBar.appearance()
The reason I would like to do this is because I have some other UIViewControllers
(that do not segue from my TabViewController
), where I would like to manually add the a UINavigationBar and it has to look just like the custom one.
Upvotes: 0
Views: 1774
Reputation: 64
My code was wrong In swift you should use
NavController = UINavigationController.init(navigationBarClass: yoursubClass, toolbarClass: AnyClass?)
Then
if let window = self.window{
window.rootViewController = NavController
}
Upvotes: 0
Reputation: 1234
If you want to customise your navigation bar to that degree, you might be better off making a subclass. The catch is that you will need to manually pass the class name into any navigation controllers that need to use it. You can do the same for a UIToolbar
if you need to, or pass nil
to use the default.
class MyNavigationBar: UINavigationBar {
override init(frame: CGRect) {
super.init(frame: frame)
// configure your nav bar here
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let navController = UINavigationController(navigationBarClass: MyNavigationBar.self, toolbarClass: nil)
For reference: https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621866-init
Upvotes: 1