我可以在UIViewController中扩展viewWillAppear吗?
问题描述:
我正在寻找一种方法来扩展从UIViewController类的函数viewWillAppear的实现,使其打印每次调用此函数时调用的视图的类名称。我可以在UIViewController中扩展viewWillAppear吗?
我知道这是不可能覆盖扩展中的函数,所以我想知道是否有任何方式来做这样的事情。
答
好的,在找到这个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)")
}
}