swift4.0 runtime method_exchang
由于项目都写完了需要适配ipad,网上搜索了一下,都有小问题
如果写在baseVC的present里面对基类代码侵入比较高,解耦并不好
如果每个都添加适配,复制代码量太大,修改也会麻烦
所以打算用runtime写 因为UIAlertController只有一个初始化方法,所以不能用,不然会无限循环,触发初始化方法
所以用了KVC来改变preferredStyle只能get的问题
public class func initMethodExchange() {
let originalSelector = #selector(UIAlertController.init(title:message:preferredStyle:))
let swizzledSelector = #selector(UIAlertController.ywx_init(title:message:preferredStyle:))
let originalMethod = class_getClassMethod(self, originalSelector)
let swizzledMethod = class_getClassMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
@objc class func ywx_init(title:String?, message:String?, preferredStyle:UIAlertControllerStyle) ->UIAlertController{
let alert = UIAlertController.init()
alert.setValue(preferredStyle.rawValue, forKeyPath:#keyPath(UIAlertController.preferredStyle))
alert.title= title
alert.message= message
if UIDevice.current.userInterfaceIdiom == .pad {
let source = UIApplication.shared.keyWindow?.rootViewController?.view
alert.popoverPresentationController?.sourceView = source
alert.popoverPresentationController?.sourceRect=CGRect(x:source!.bounds.midX, y: source!.bounds.midY, width:0, height:0)
}
return alert
}