gpt4 book ai didi

swift - 要求协议(protocol)实现者用 @objc 标记函数

转载 作者:行者123 更新时间:2023-11-30 11:09:46 31 4
gpt4 key购买 nike

我正在使用UIMenuController,我可以在其中添加一个菜单项,该菜单项在其初始化中采用#selector

现在我可能会在几个不同的地方抓取调用,因此想要编写一个协议(protocol)来确保我想要从响应者链中抓取操作的每个地方都实现正确的函数签名。

我的问题是,如何要求协议(protocol)实现者将 @objc 添加到协议(protocol)的函数中?否则不会被调用。

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]

最佳答案

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

@objc protocol PrintToConsoleProtocol {
func printToConsole()
}

extension PDFView: PrintToConsoleProtocol {
func printToConsole() {
print("Printing to console.. from PDFView!")
}
}

关于swift - 要求协议(protocol)实现者用 @objc 标记函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52302748/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com