确定哪个 NSView 实例发起了 mouseDown:
我有一个带有 25 个 myGameTile 块的游戏板,它是 NSView 的子类。 在 mouseDown: 我想确定我单击了哪个图块并将 ivar 设置为代表值。
例如,如果我单击图块 12,请将 clickedTile 设置为“12”或唯一代表该特定实例的某个值。
我会打开从整数值 12 一直到某种内省/反思的任何内容,尽管内置功能和优雅比黑客、运行时包装和修改更可取。 不过,我知道我可能别无选择,只能依赖这些解决方案,所以也请回答这些问题。 我想知道我所有的选择。 谢谢!
I have a gameboard with 25 tiles of myGameTile, a subclass of NSView.
In mouseDown: I want to determine which tile I clicked on and set an ivar to a representative value.
e.g. If I click on tile 12, set clickedTile to "12" or some value that uniquely represents that particular instance.
I'm open anything from the integer value 12 all the way to some sort of introspection/reflection, though built-in features and elegance are preferable to hacks, runtime wrappers, and modification. Still, I'm aware that I may have no choice but to rely on those solutions, so please to answer with those as well. I'd like to know all my options. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以子类化 NSView 并覆盖 标记方法,如文档中所写。
You could subclass NSView and override the tag method, as written in the documentation.
您有几种可能性:
如果您在 Tile 视图中处理 mouseDown,那么您需要将 self 映射到tile ID。 有三种简单的方法可以做到这一点:
显然,使用标签是最简单的,只要因为您没有将该标签用于其他任何用途。
或者,您可以在父视图上实现 hitTest ,并返回父视图,然后在父视图中处理 mouseDown 。 然后 mouseDown 就会知道点击的位置,从而知道它是哪个图块。
You have several possibilities:
If you handle the mouseDown in the Tile view, then you need to map self to the tile ID. There are three easy ways to do this:
Clearly, using the tag is the easiest, as long as you are not using the tag for anything else.
Alternatively, you could implement hitTest on the parent view, and return the parent view, and then handle the mouseDown in the parent view. Then mouseDown will know where the hit is and hence which tile it is.
我认为 hitTest: 会做你想做的。 像这样的事情:
I think hitTest: will do what you want. Something like this: