我有一组 View Controller ,其中有一个菜单栏按钮。我为那些 viewControllers 创建了一个协议(protocol)来采用。此外,我还扩展了协议(protocol)以添加默认功能。
我的协议(protocol)看起来像,
protocol CenterViewControllerProtocol: class {
var containerDelegate: ContainerViewControllerProtocol? { get set }
func setupMenuBarButton()
}
而且,扩展看起来像这样,
extension CenterViewControllerProtocol where Self: UIViewController {
func setupMenuBarButton() {
let barButton = UIBarButtonItem(title: "Menu", style: .Done, target: self, action: "menuTapped")
navigationItem.leftBarButtonItem = barButton
}
func menuTapped() {
containerDelegate?.toggleSideMenu()
}
}
我的 viewController 采用协议(protocol) -
class MapViewController: UIViewController, CenterViewControllerProtocol {
weak var containerDelegate: ContainerViewControllerProtocol?
override func viewDidLoad() {
super.viewDidLoad()
setupMenuBarButton()
}
}
我的按钮可以很好地显示,但是当我点击它时,应用程序崩溃了
[AppName.MapViewController menuTapped]: unrecognized selector sent to instance 0x7fb8fb6ae650
如果我在 ViewController 中实现该方法,它工作正常。但是我会在所有符合协议(protocol)的 viewController 中复制代码。
我做错了什么吗? 提前致谢。
最佳答案
目前似乎不支持使用协议(protocol)扩展。根据fluidsonic's回答here :
In any case all functions you intend to use via selector should be marked with dynamic or @objc. If this results in an error that @objc cannot be used in this context, then what you are trying to do is simply not supported."
在您的示例中,我认为解决此问题的一种方法是创建 UIBarButtonItem 的子类,只要点击它就会调用一个 block 。然后您可以在该 block 内调用 containerDelegate?.toggleSideMenu()
。
关于ios - 在协议(protocol)扩展中添加目标操作失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33918990/