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文件

  1. import UIKit
  2.  
  3. extension UIViewController {
  4. public override class func initialize() {
  5.  
  6. // make sure this isn't a subclass
  7. if self !== UIViewController.self {
  8. return
  9. }
  10.  
  11. struct DispatchToken {
  12. static var token: dispatch_once_t = 0
  13. }
  14.  
  15. dispatch_once(&DispatchToken.token) {
  16. let originalSelector = #selector(UIViewController.viewDidLoad)
  17. let swizzledSelector = #selector(self.lw_viewDidLoad)
  18.  
  19. let originalMethod = class_getInstanceMethod(self,originalSelector)
  20. let swizzledMethod = class_getInstanceMethod(self,swizzledSelector)
  21.  
  22. let addMethod = class_addMethod(self,originalSelector,method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod))
  23.  
  24. if addMethod {
  25. class_replaceMethod(self,swizzledSelector,method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod))
  26. }else {
  27. method_exchangeImplementations(originalMethod,swizzledMethod)
  28. }
  29.  
  30. }
  31. }
  32.  
  33. func lw_viewDidLoad() {
  34. print("viewDidLoad: \(NSStringFromClass(self.classForCoder))")
  35. let albumClassName = NSStringFromClass(self.classForCoder)
  36. if albumClassName.containsString("SwiftAlbum") {
  37. self.view.backgroundColor = UIColor.init(colorLiteralRed: 244/255,green: 244/255,blue: 244/255,alpha: 1)
  38. }
  39. }
  40. }
  41.  
  42.  
  43. class AppLoad: NSObject {
  44.  
  45.  
  46. }

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

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

猜你在找的Swift相关文章