jamryu
jamryu

Reputation: 698

How to avoid writing same code over again in UIViewController in Swift?

I have the following piece of code that I write in every UIViewController:

var navBar = self.navigationController?.navigationBar
    navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

I don't want to write these in every UIViewController that I create. I am lazy and I don't want to repeat myself. I can't add it in extension. So what can I do to not have to write this piece of code when I create UIViewController?

Upvotes: 0

Views: 75

Answers (2)

Charlie Cai
Charlie Cai

Reputation: 301

1.Use a base UIViewController such as BaseViewController and put this code inside viewDidLoad and replace UIViewController with BaseViewController.

2.You may not want to do anything to UIViewController.Then,you may come across the term AOP.for example Java use AOP a lot.

You can use AOP framework like Aspects.

Upvotes: 1

shingo.nakanishi
shingo.nakanishi

Reputation: 2827

You can use the default implementation protocol in this case.

Create default implementation protocol:

import Foundation
import UIKit

protocol TitleSetupable: AnyObject {
    func setupTitle()
}

extension TitleSetupable where Self: UIViewController {
    func setupTitle() {
        var navBar = self.navigationController?.navigationBar
        navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
}

Use in your ViewController:

class YourViewController: UIViewController, TitleSetupable {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTitle()
    }
}

Upvotes: 1

Related Questions