ios - 在协议(protocol)扩展中添加目标操作失败

标签 ios swift protocol-extension

我有一组 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/

相关文章:

ios - CATransform3DMakeRotation 在动画过程中隐藏了一半的 UIView

swift - 扩展现有协议(protocol)以使用默认实现实现另一个协议(protocol)

ios - 使用 UIScrollView 进行分页

ios - Xcode 12 HaishinKit lib 构建错误 : Undefined symbols for architecture x86_64

IOS SWIFT 4 使用区域设置将字符串转换为十进制

swift - 如何在swift 4中的 Collection View 中实现字符串数组的分页

ios - 快速编辑 UITableView

swift - ObjC 协议(protocol)的协议(protocol)扩展

Swift 协议(protocol)扩展静态方法与父类(super class)和子类的调度

ios - 如何在 SwiftUI 中保留 View 结构列表?