【发布时间】:2016-05-13 19:23:22
【问题描述】:
我有一个名为NakedNavigationBar 的协议。
我还有一个扩展,它扩展了所有符合 NakedNavigationBar 的 UIViewControllers。
问题在于,我想在扩展中添加默认行为,以便在 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,但这使得我所有的UIViewControllers 立即符合NakedNavigationBar 而不仅仅是我选择的那些。
【问题讨论】:
-
即使编译后的方法也行不通。调配方法会影响每个
UIViewController,而不仅仅是符合您协议的那些。 -
好点:/你能想出一个解决办法吗?
标签: ios swift uiviewcontroller swift-extensions method-swizzling