Swift 方法交换
2021-08-11 本文已影响0人
大也
extension UIViewController {
public class func initializeMethod(){
var originalSelectorArr: [Selector] = Array()
originalSelectorArr.append(#selector(UIViewController.viewDidAppear(_:)))
originalSelectorArr.append(#selector(UIViewController.viewDidDisappear(_:)))
var swizzledSelectorArr: [Selector] = Array()
swizzledSelectorArr.append(#selector(UIViewController.alertController_viewDidAppear(animated:)))
swizzledSelectorArr.append(#selector(UIViewController.alertController_viewDidDisappear(animated:)))
for index in 0 ..< originalSelectorArr.count {
let originalSelector: Selector = originalSelectorArr[index]
let swizzledSelector: Selector = swizzledSelectorArr[index]
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
//在进行 Swizzling 的时候,需要用 class_addMethod 先进行判断一下原有类中是否有要替换方法的实现
let didAddMethod: Bool = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
//如果 class_addMethod 返回 yes,说明当前类中没有要替换方法的实现,所以需要在父类中查找,这时候就用到 method_getImplemetation 去获取 class_getInstanceMethod 里面的方法实现,然后再进行 class_replaceMethod 来实现 Swizzing
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
}
@objc func alertController_viewDidAppear(animated: Bool) {
if (ADAlertControllerPriorityQueue.shareInstance().checkShowNextValidity() == true) {
ADAlertControllerPriorityQueue.shareInstance().showNext()
}
self.alertController_viewDidAppear(animated: animated)
}
@objc func alertController_viewDidDisappear(animated: Bool) {
if ADAlertControllerPriorityQueue.shareInstance().currentAlertController?.targetViewController == self, ADAlertControllerPriorityQueue.shareInstance().currentAlertController?.autoHidenWhenTargetViewControllerDisappear == true {
ADAlertControllerPriorityQueue.shareInstance().currentAlertController?.deleteWhenHiden = false
ADAlertControllerPriorityQueue.shareInstance().currentAlertController?.hiden()
}else if(ADAlertControllerPriorityQueue.shareInstance().checkShowNextValidity() == true){
ADAlertControllerPriorityQueue.shareInstance().showNext()
}
self.alertController_viewDidDisappear(animated: animated)
}
}