Skip to content

Instantly share code, notes, and snippets.

@vvit
Last active November 23, 2017 09:10
Show Gist options
  • Save vvit/d9afec77fb8333686cdb894ab5a14b1e to your computer and use it in GitHub Desktop.
Save vvit/d9afec77fb8333686cdb894ab5a14b1e to your computer and use it in GitHub Desktop.
Swizzling
// AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIViewController.doSwizzleStuff()
}
// extension
// MARK: - Swizzling
private var hasSwizzled = false
extension UIViewController {
final public class func doSwizzleStuff() {
guard !hasSwizzled else { return }
hasSwizzled = true
// make sure this isn't a subclass
if self !== UIViewController.self {
return
}
let originalSelector = #selector(viewDidLoad)
let swizzledSelector = #selector(my_viewDidLoad)
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
guard originalMethod != nil, swizzledMethod != nil else {
return
}
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
@objc func my_viewDidLoad() {
self.my_viewDidLoad()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment