ios - UIAccessibilityCustomAction 选择器不适用于静态方法
问题描述
selector
当我在参数中 传递静态/类方法时UIAccessibilityCustomAction
,它不会被触发。相同的方法适用于手势识别器/添加目标功能
自定义操作已正确设置和宣布。所以设置没有问题。但是当我双击时staticTest
不会触发。如果我将实例方法传递给它,它就可以工作。
代码设置不起作用:
// does not work
newView.accessibilityCustomActions?.append(
UIAccessibilityCustomAction(
name: "staticTest test action",
target: ViewController.self,
selector: #selector(ViewController.staticTest)))
代码示例:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let newView = UIView(frame: CGRect(x: 20, y: 20, width: 300, height: 300))
newView.backgroundColor = UIColor.red
view.isUserInteractionEnabled = true
view.addSubview(newView)
newView.isAccessibilityElement = true
// works
newView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(instanceTest)))
// works
newView.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: "instanceTest test action", target: self, selector: #selector(instanceTest))
]
// works
newView.addGestureRecognizer(
UITapGestureRecognizer(
target: ViewController.self,
action: #selector(ViewController.staticTest)))
// does not work
newView.accessibilityCustomActions?.append(
UIAccessibilityCustomAction(
name: "staticTest test action",
target: ViewController.self,
selector: #selector(ViewController.staticTest)))
}
@objc static func staticTest() -> Bool {
print("staticTest")
return true
}
@objc func instanceTest() -> Bool {
print("InstanceTest")
return true
}
}
解决方案
我试过你的代码,很难相信观察结果。然后我检查了苹果文档,这是我的分析。
尽管苹果文档对使用静态/类函数作为选择器保持沉默。这在措辞中间接提到了。 https://developer.apple.com/documentation/uikit/uiaccessibilitycustomaction/1620499-init
对于 UIAccessibilityCustomAction:目标:执行操作的对象。选择器:当您要执行操作时要调用的目标选择器。
在您的代码中,目标是 ViewController 对象,但很难说选择器属于该对象,因为它是一个静态/类函数。实际上,swift 甚至不允许使用对象调用静态函数。话虽如此,为什么静态函数与手势识别器一起工作还是有争议的。 https://developer.apple.com/documentation/uikit/uigesturerecognizer/1624211-init
目标的定义在这里略有不同。目标:一个对象,它是接收者在识别手势时发送的动作消息的接收者。action:一个选择器,标识目标实现的方法来处理接收器识别的手势。
因此,您的代码完全匹配目标定义,因为 self 是应该接收手势的对象。但是动作定义并不完全匹配,因为目标(它是一个对象而不是一个类)实际上没有实现静态函数。
据我了解,静态函数需要避免作为基于文档的选择器。
推荐阅读
- sql - postgres 使用 over partition 对动态行求和
- excel - 查找 Excel 文件损坏的原因
- prolog - 启发式表转换为 prolog 事实突出显示错误
- d3.js - D3 - 带折线图的堆叠条形图双轴
- go - 在 golang 中创建二维字符串数组
- php - 带有codeigniter的Restfull API没有从帖子网址中获取价值
- c# - Photon Realtime:PluginHost.HttpRequest 参数“异步”是什么意思?
- django - 删除对象,从 ListView 到 DeleteView
- javascript - 为什么 moment().format() 会在未来六个小时内创建一个日期对象?
- asp.net - 在更新按钮上获取行值