Last active
August 29, 2019 08:56
-
-
Save Pulichev/9709120149c66cce1c9cfc34c3ec194e to your computer and use it in GitHub Desktop.
UIViewController viewDidLoad swizzling example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIViewController { | |
static let shared : UIViewController = { | |
$0.initialize() | |
return $0 | |
} (UIViewController()) | |
func initialize() { | |
let swizzleClosure: () = { | |
UIViewController().swizzleViewDidLoad() | |
}() | |
swizzleClosure | |
} | |
// MARK: - Helpers | |
func swizzleViewDidLoad() { | |
let originalViewDidLoadSelector = #selector(UIViewController.viewDidLoad) | |
let swizzledViewDidLoadSelector = #selector(UIViewController.newViewDidLoad) | |
guard let originalViewDidLoadMethod = class_getInstanceMethod(UIViewController.self, originalViewDidLoadSelector), | |
let swizzledViewDidLoadMethod = class_getInstanceMethod(UIViewController.self, swizzledViewDidLoadSelector) else { | |
return | |
} | |
let didAddViewDidLoadMethod = class_addMethod(UIViewController.self, originalViewDidLoadSelector, method_getImplementation(swizzledViewDidLoadMethod), method_getTypeEncoding(swizzledViewDidLoadMethod)) | |
if didAddViewDidLoadMethod { | |
class_replaceMethod(UIViewController.self, swizzledViewDidLoadSelector, method_getImplementation(originalViewDidLoadMethod), method_getTypeEncoding(swizzledViewDidLoadMethod)) | |
} else { | |
method_exchangeImplementations(originalViewDidLoadMethod, swizzledViewDidLoadMethod) | |
} | |
} | |
// MARK: - Method Swizzling. | |
@objc func newViewDidLoad() { | |
// FIXME: add necessary things. | |
self.newViewDidLoad() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment