我有一個協議叫NakedNavigationBar
。Swift - 擴展類只有當它符合使用方法調配的協議
我也有一個擴展,擴展所有UIViewController
s符合NakedNavigationBar
。
問題是在擴展中,我想添加默認行爲,以便在初始化UIViewController
時,我們使用方法在UIViewController
上調整。
這是我的協議和擴展:
import UIKit
protocol NakedNavigationBar
{
}
extension NakedNavigationBar where Self: UIViewController
{
public override class func initialize()
{
struct Static
{
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token)
{
let originalSelector = #selector(viewWillAppear(_:))
let swizzledSelector = #selector(nakedNavigationBar_viewWillAppear(_:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod))
if didAddMethod
{
class_replaceMethod(self,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod))
}
else
{
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
// MARK: - Swizzling Methods
func nakedNavigationBar_viewWillAppear(animated: Bool)
{
self.nakedNavigationBar_viewWillAppear(animated)
print("VWA Swizzling...")
// Hide the navigation bar
_setNavigationBarVisible(isVisible: false)
}
// MARK: -
private func _setNavigationBarVisible(isVisible isVisible: Bool)
{
// (Changes background and shadow image)
}
}
本質上告訴我,我不能擴展協議,因爲它不具備UIViewController
方法。但據我所知,where Self: UIViewController
應該使它只能在UIViewController
上工作,只有當視圖控制器符合NakedNavigationBar
時才能擴展視圖控制器。
原來延長了extension UIViewController: NakedNavigationBar
但是這使得我所有的UIViewController
小號瞬間符合NakedNavigationBar
而不是隻有我選擇的人。
即使編譯你的方法也行不通。調整方法會影響每個UIViewController,而不僅僅是那些符合你的協議的方法。 – dan
好點:/你能想到解決辦法嗎? –