简体   繁体   中英

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 ?

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.

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()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM