我有一个协议叫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
好点:/你能想到解决办法吗? –