gpt4 book ai didi

swift - 我可以在 UIViewController 中扩展 viewWillAppear 吗?

转载 作者:搜寻专家 更新时间:2023-11-01 07:18:15 24 4
gpt4 key购买 nike

我正在寻找一种方法来扩展 UIViewController 类的函数 viewWillAppear 的实现,以使其在每次调用此函数时打印所调用 View 的类名。

我知道不可能覆盖扩展中的函数,所以我想知道是否有任何方法可以做这样的事情。

最佳答案

好的,找到这个之后http://nshipster.com/swift-objc-runtime/我尝试了类似的东西并且可以达到预期的结果。

代码如下:

extension UIViewController {
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}

// make sure this isn't a subclass
if self !== UIViewController.self {
return
}

dispatch_once(&Static.token) {
let originalSelector = #selector(UIViewController.viewWillAppear(_:))
let swizzledSelector = #selector(UIViewController.nsh_viewWillAppear(_:))

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

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

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

// MARK: - Method Swizzling

func nsh_viewWillAppear(animated: Bool) {
self.nsh_viewWillAppear(animated)
NSLog("viewWillAppear: \(self)")
}
}

关于swift - 我可以在 UIViewController 中扩展 viewWillAppear 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40659125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com