在Swift 4中,Swizzling不再起作用。
Method 'initialize()'定义了Objective-C类方法'initialize',这在Swift中是不允许的。
我已经找到了解决方案,因此想为其他人留下问题和答案。
在Swift 4中,Swizzling不再起作用。
Method 'initialize()'定义了Objective-C类方法'initialize',这在Swift中是不允许的。
我已经找到了解决方案,因此想为其他人留下问题和答案。
initialize()不再公开: 方法'initialize()'定义了Objective-C类方法'initialize',Swift不允许
现在的解决方法是通过公共静态方法运行您的交换代码。
例如
在扩展中: (此扩展用于kickstarter开源代码: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 */
}
}
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
}