0

我在每个 UIViewController 中编写了以下代码:

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

我不想在UIViewController我创建的每一个中都写这些。我很懒惰,我不想重复自己。我无法添加它extension。那么我可以做些什么来在创建时不必编写这段代码UIViewController呢?

4

2 回答 2

1

在这种情况下,您可以使用默认的实现协议。

创建默认实现协议:

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]
    }
}

在您的 ViewController 中使用:

class YourViewController: UIViewController, TitleSetupable {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTitle()
    }
}
于 2020-05-31T03:34:16.987 回答
1

1.使用一个基本的UIViewController,比如BaseViewController,把这段代码放在viewDidLoad里面,用BaseViewController替换UIViewController。

2.你可能不想对UIViewController做任何事情。然后,你可能会遇到AOP这个词。例如Java使用AOP很多。

您可以使用 AOP 框架,如 Aspects。

于 2020-05-31T09:39:36.403 回答