Swift Swizzled

前端之家收集整理的这篇文章主要介绍了Swift Swizzled前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

objc中出于安全性和一致性考虑,用+(void)load()来实现
swift中load()方法不起作用了,在swift中写load()方法编译器会提示错误
可以用initialize() 或者是直接写在application(application: UIApplication,didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool

下面是在initialize() 实现的例子,修改项目中所有UIViewController的背景色
新建一个项目SwiftAlbum,为了代码修改起来方便,新建了一个AppLoad.swift文件

import UIKit

extension UIViewController {
    public override class func initialize() {

        // make sure this isn't a subclass
        if self !== UIViewController.self {
            return
        }

        struct DispatchToken {
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&DispatchToken.token) {
            let originalSelector = #selector(UIViewController.viewDidLoad)
            let swizzledSelector = #selector(self.lw_viewDidLoad)

            let originalMethod = class_getInstanceMethod(self,originalSelector)
            let swizzledMethod = class_getInstanceMethod(self,swizzledSelector)

            let addMethod = class_addMethod(self,originalSelector,method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod))

            if addMethod {
                class_replaceMethod(self,swizzledSelector,method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod))
            }else {
                method_exchangeImplementations(originalMethod,swizzledMethod)
            }

        }
    }

    func lw_viewDidLoad() {
        print("viewDidLoad: \(NSStringFromClass(self.classForCoder))")
        let albumClassName = NSStringFromClass(self.classForCoder)
        if albumClassName.containsString("SwiftAlbum") {
            self.view.backgroundColor = UIColor.init(colorLiteralRed: 244/255,green: 244/255,blue: 244/255,alpha: 1)
        }
    }
}


class AppLoad: NSObject {


}

通过print(“viewDidLoad:(NSStringFromClass(self.classForCoder))”)打印可以看到,项目中新建的UIViewController,都有一个工程名前缀,比如SwiftAlbum.XXXViewController

参考地址:http://nshipster.com/swift-objc-runtime/

猜你在找的Swift相关文章