7

Swizzling 在 Swift 4 中不再起作用。

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

这是我找到的解决方案,因此想将问题和答案留给其他人。

4

1 回答 1

7

initialize() 不再公开:Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift

所以现在的方法是通过公共静态方法运行你的调酒代码。

例如

在扩展中:(本扩展在kickstarted开源代码中使用:https ://github.com/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开源代码中使用:https ://github.com/kickstarter/ios-oss/blob/7c827770813e25cc7f79a28fa151cd713efe936f/Kickstarter-iOS/AppDelegate.swift#L33 )

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

另一种方法是使用单例:

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
}
于 2017-09-22T09:15:15.733 回答