NSApp.sendAction() 仅在一段时间后有效

NSApp.sendAction() only works after some time

我想要一个 ViewController (ContainerVC) 对子自定义视图 (ChildView) 的点击做出反应。

ChildView 中,我覆盖 mouseDown(_:) 来处理点击。在这种方法中,我尝试通过 NSApp.sendAction(#selector(ContainerVC.childViewClicked(_:)), to: nil, from: self).

调用 ContainerVC 目标

由于某种原因,sendAction 方法首先失败(即 returns false)。 NSApp.target(forAction: #selector(ContainerVC.childViewClicked(_:)) 也为零。

一段时间后(通常是在我疯狂点击自定义视图一段时间后),目标得到解析,一切正常,ContainerVC.childViewClicked(_:) 被调用。

在 time/how 次点击目标得到解决后,我找不到系统的模式(除了我对我的 mac 大喊大叫的强度)。

有趣的是,当我通过 let window = NSWindow(contentViewController: ContainerVC()).

添加 ContainerVC 到 window 时,它工作正常

当我将 ContainerVC 添加到拆分视图时,会出现上述奇怪的行为:

self.addSplitViewItem(NSSplitViewItem(viewController: ContainerVC())

我检查了 CustomView 的响应链。 ContainerVC 按预期出现在链中。链中没有其他 类 实现 childViewClicked(_:).

如果有人能告诉我有关 NSApp.sendAction(_:) 的内部工作原理以及为什么目标一开始为 nil 的原因,我将不胜感激。

将 ViewController 添加到 SplitView 以正确连接时是否需要额外的步骤?

来自 sendAction(_:to:from:) 的文档:

If aTarget is nil, sharedApplication looks for an object that can respond to the message—that is, an object that implements a method matching anAction. It begins with the first responder of the key window.

当 ChildView 不是第一响应者时,sendAction(_:to:from:) 不起作用。使用

func `try`(toPerform action: Selector, with object: Any?) -> Bool

例如

self.`try`(toPerform: #selector(ContainerVC.childViewClicked(_:)), with: self)

哪个做你想要的:

If the receiver responds to anAction, it invokes the method with anObject as the argument and returns YES. If the receiver doesn’t respond, it sends this message to its next responder with the same selector and object.