swift - 要求协议实现者用@objc 标记函数
问题描述
我正在玩UIMenuController
我可以添加一个菜单项的地方,该菜单项#selector
在其初始化中采用 a 。
现在我可能会在几个不同的地方抓取调用,因此想编写一个协议来确保我想从响应链中抓取动作的每个地方都实现正确的函数签名。
我的问题是,我如何要求协议实现者添加@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]
解决方案
您可以在 -keyword@objc
之前添加protocol
以使其成为 objc 协议,并采用它将现在存在于实现者中的协议中的所有功能解释为@objc
在它之前具有。
@objc protocol PrintToConsoleProtocol {
func printToConsole()
}
extension PDFView: PrintToConsoleProtocol {
func printToConsole() {
print("Printing to console.. from PDFView!")
}
}
推荐阅读
- python-3.x - ValueError:layersequential_7 的输入 0 与 layer 不兼容::预期 min_ndim=4,发现 ndim=2。收到的完整形状:(无,1024)
- php - 将键号分配给 php 数组对象
- scikit-learn - SKLearn中isolation_forest中的decision function和score_samples有什么区别
- git - 文件未添加到 Github 上的存储库 - 存储库显示为空
- reactjs - 难以创建基本行(@react-three/fiber 和 Typescript)
- http - 响应的数据部分中没有数据。我该如何解决?
- python - 将更改的数据传递给另一个正在运行的代码
- html - 如何用html和css实现图片中的侧边栏外观
- jquery - 带有进度条多个实例的 Momentjs 不起作用
- ssl - 将 Power BI 连接到 BigQuery 问题 - SSL 验证失败