Kelvin Lau
Kelvin Lau

Reputation: 6781

Using extensions to give a value to an existing property

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

Answers (2)

Quanlong
Quanlong

Reputation: 25476

According to Swift Programming Guide, Extensions in Swift can:

  • Add computed properties and computed type properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol

Extensions is used to extent/add new behaviours, what you need is to override the default behaviours. You can achieve this by subclass UINavigationBaror 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

rshev
rshev

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

Related Questions