swift 4 中的方法调配

编程入门 行业动态 更新时间:2024-10-28 16:25:03
本文介绍了swift 4 中的方法调配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Swift 4 中的 Swizzling 不再有效.

Swizzling in Swift 4 no longer works.

方法 'initialize()' 定义了 Objective-C 类方法 'initialize',这是 Swift 不允许的

这是我找到的解决方案,所以想把问题和答案留给其他人.

This is something I have found a solution to so wanted to leave the questions and answer for others.

推荐答案

initialize() 不再暴露:Method 'initialize()' 定义了 Objective-C 类方法 'initialize',这是 Swift 不允许的

initialize() is no longer exposed: Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift

所以现在的方法是通过公共静态方法运行您的 swizzle 代码.

So the way to do it now is to run your swizzle code via a public static method.

例如

在扩展中:(这个扩展在kickstarted开源代码中使用:github/kickstarter/ios-oss/blob/master/Library/DataSource/UIView-Extensions.swift)

In the extension: (This extension is used in the kickstarted open source code: github/kickstarter/ios-oss/blob/master/Library/DataSource/UIView-Extensions.swift)

private var hasSwizzled = false extension UIView { final public class func doBadSwizzleStuff() { guard !hasSwizzled else { return } hasSwizzled = true swizzle(self) /* This is pseudo - run your method here */ } }

在应用委托中:(kickstarted开源代码中使用了这个方法:github/kickstarter/ios-oss/blob/7c827770813e25cc7f79a28fa151cd713efe936f/Kickstarter-iOS/AppDelegate.swift#L33)

In the app delegate: (This method is used in the kickstarted open source code: github/kickstarter/ios-oss/blob/7c827770813e25cc7f79a28fa151cd713efe936f/Kickstarter-iOS/AppDelegate.swift#L33)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIView.doBadSwizzleStuff() }

另一种方法是使用单例:

Another way is to use a singleton:

extension UIView { static let shared : UIViewController = { $0.initialize() return $0 }(UIViewController()) func initialize() { // make sure this isn't a subclass guard self === UIViewController.self else { return } let swizzleClosure: () = { UIViewController().swizzle() /* This is pseudo - run your method here */ }() swizzleClosure } } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: UIApplicationLaunchOptionsKey: Any]?) -> Bool { _ = UIViewController.shared }

更多推荐

swift 4 中的方法调配

本文发布于:2023-11-26 06:14:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632957.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!