Reputation: 6781
I want all UINavigationBar
objects to have a default value of [NSFontAttributeName: UIFont(name: "Soft Elegance", size: 18)!]
in it's titleTextAttributes
property.
In a UIViewController
, this is how I would set it:
override func viewDidLoad() {
super.viewDidLoad()
navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Soft Elegance", size: 18)!]
}
However, I have several UIViewControllers
that all require this line of code. I know that extensions
can provide behaviours for the entire class, but I'm failing to make this happen for my case:
extension UINavigationBar {
var titleTextAttributes: [NSObject: AnyObject]! {
return [NSFontAttributeName: UIFont(name: "Soft Elegance", size: 18)!]
}
}
Are there any ways to accomplish this via extensions
?
Upvotes: 1
Views: 62
Reputation: 25476
According to Swift Programming Guide, Extensions in Swift can:
Extensions is used to extent/add new behaviours, what you need is to override the default behaviours. You can achieve this by subclass UINavigationBar
or UIViewController
like,
class BaseViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Soft Elegance", size: 18)!]
}
}
Then use BaseViewController
to replace existing UIViewController
Upvotes: 1
Reputation: 4176
You want UIAppearance
:
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Soft Elegance", size: 18)!]
This will affect all UINavigationBars in the app.
Upvotes: 2