【问题标题】:How to avoid writing same code over again in UIViewController in Swift?如何避免在 Swift 的 UIViewController 中再次编写相同的代码?
【发布时间】:2020-05-31 01:55:40
【问题描述】:

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

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

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

【问题讨论】:

  • 你不能把这段代码提取到一个函数中,将导航控制器作为参数传递吗?
  • 另外,密钥类型已经知道是NSAttributedString.Key,所以你可以写:[.foregroundColor: UIColor.white]

标签: swift uiviewcontroller uinavigationcontroller uinavigationbar swift5.2


【解决方案1】:

1.使用BaseViewController之类的基本UIViewController并将此代码放入viewDidLoad中并将UIViewController替换为BaseViewController。

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

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

【讨论】:

    【解决方案2】:

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

    创建默认实现协议:

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

    【讨论】:

    • 在这样的类声明中调用函数是无效的。这不是 Ruby,无论好坏。
    • @Alexander-ReinstateMonica 是的。我添加 viewDidLoad。
    • 我知道我们可以使用协议和/或扩展来最大程度地减少冗余,但我问这个问题是希望有人有不同的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2023-04-04
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多