要求协议实现者使用@objc标记函数

问题描述 投票:0回答:1

我正在玩UIMenuController,在那里我可以添加一个菜单项,在其初始化中需要一个#selector

现在我可以在几个不同的地方抓住呼叫,因此想要编写一个协议,以确保我想从响应器链中获取动作的每个地方实现正确的功能签名。

我的问题是,我如何要求协议实现者将@objc添加到协议的功能?否则不会被调用。

protocol PrintToConsoleProtocol {
    func printToConsole()
}

extension PDFView: PrintToConsoleProtocol {
    // PDFView conforms to PrintToConsoleProtocol without @objc!
    // So protocol does not make sure the implementor will be callable
    // despite having adopted it.
    @objc func printToConsole() {
        print("Printing to console.. from PDFView!")
    }
}

用于添加菜单条目的代码:

let printToConsole = UIMenuItem(
    title: "Print To Console",
    action: #selector(PrintToConsoleProtocol.printToConsole)
)
UIMenuController.shared.menuItems = [printToConsole]
swift swift-protocols
1个回答
0
投票

您可以在@objc关键字之前添加protocol,使其成为objc协议,并采用它将现在在实现者中存在的协议中的所有函数解释为在其之前具有@objc

@objc protocol PrintToConsoleProtocol {
    func printToConsole()
}

extension PDFView: PrintToConsoleProtocol {
    func printToConsole() {
        print("Printing to console.. from PDFView!")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.