swift - Can I extend viewWillAppear in UIViewController? -
i looking way extend implementation of function viewwillappear uiviewcontroller class make print class name of view called everytime function called.
i know it's not possible override functions in extensions wonder if there way this.
ok, after finding http://nshipster.com/swift-objc-runtime/ tried similar , achieve desired result.
the code looks like:
extension uiviewcontroller { public override class func initialize() { struct static { static var token: dispatch_once_t = 0 } // make sure isn't 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)") } }
Comments
Post a Comment