objc中出于安全性和一致性考虑,用+(voID)load()来实现
swift中load()方法不起作用了,在swift中写load()方法编译器会提示错误,
可以用initialize() 或者是直接写在application(application: UIApplication,dIDFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool
下面是在initialize() 实现的例子,修改项目中所有UIVIEwController的背景色
新建一个项目SwiftAlbum,为了代码修改起来方便,新建了一个AppLoad.swift文件
import UIKitextension 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 Swizzled全部内容,希望文章能够帮你解决Swift Swizzled所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)