我正在玩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]
您可以在@objc
关键字之前添加protocol
,使其成为objc协议,并采用它将现在在实现者中存在的协议中的所有函数解释为在其之前具有@objc
。
@objc protocol PrintToConsoleProtocol {
func printToConsole()
}
extension PDFView: PrintToConsoleProtocol {
func printToConsole() {
print("Printing to console.. from PDFView!")
}
}