【问题标题】:How to swizzle viewDidLoad method in UIViewController in swift 4? initialize() is deprecated in swift 4如何在 swift 4 中调整 UIViewController 中的 viewDidLoad 方法?在 swift 4 中不推荐使用 initialize()
【发布时间】:2017-10-17 10:21:43
【问题描述】:

我想在UIViewController 扩展中调配viewDidLoad,但initialize() 方法在swift3 中被覆盖并且工作不受swift4 支持。谁能给我任何解决方案?我在swift3 中的代码如下。

    extension UIViewController {

    open override class func initialize() {

        guard self === UIViewController.self else { return }
        swizzling(self)
    }

    // MARK: - Method Swizzling

    func nsh_viewDidLoad() {
        self.nsh_viewDidLoad()

        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
    }

并且有一个全局方法

private let swizzling: (UIViewController.Type) -> () = { viewController in

    let originalSelector = #selector(viewController.viewDidLoad)
    let swizzledSelector = #selector(viewController.nsh_viewDidLoad)

    let originalMethod = class_getInstanceMethod(viewController, originalSelector)
    let swizzledMethod = class_getInstanceMethod(viewController, swizzledSelector)

    let didAddMethod = class_addMethod(viewController, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

    if didAddMethod {
        class_replaceMethod(viewController, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
}

【问题讨论】:

  • 您能先解释一下为什么要调酒吗?通常这意味着你做错了什么......
  • 您是否理解您正在尝试做的是一种非常复杂的方法来做一件可以使用一个子类来实现的非常简单的事情?例如。子类化 UINavigationController 以隐藏其控制器上的所有后退按钮标题,然后只使用您的子类而不是 UINavigationController
  • 我正在尝试将现有项目转换为 swift 4,因此如果我将 UINavigationController 子类化,我需要更改项目中的许多类。但是感谢您的建议,如果 swizzling 不起作用,这将是我的替代解决方案。
  • 如果您想快速完成,只需从您的AppDelegate 中调用initialize

标签: ios swift uiviewcontroller swift4 swizzling


【解决方案1】:

我在 AppDelegate 中添加了以下代码,而不是 swizzling

let barButtonItemAppearance = UIBarButtonItem.appearance()
        barButtonItemAppearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.clear], for: .normal)
        barButtonItemAppearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.clear], for: .highlighted)

【讨论】:

    猜你喜欢
    • 2018-03-15
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 2018-04-19
    • 2018-12-24
    相关资源
    最近更新 更多