NSView 通过 NSTextView 接收点击事件
我在 NSView 中有一个不可编辑、不可选择的 NSTextView。我需要 NSView 在单击文本视图时接收单击事件 - 基本上我需要单击事件就像文本视图根本不存在一样。显然我只会使用
textView:clickedOnCell:inRect:atIndex:
文本视图委托方法,但我需要捕获单击事件,以检测双击和类似的事情。
I have a NSTextView, non-editable, non-selectable, in a NSView. I need the NSView to receive click events when the text view is clicked - basically I need the click events to act as though the text view doesn't even exist. Obviously I would just use the
textView:clickedOnCell:inRect:atIndex:
text view delegate method, but I need to capture the click event, to detect double-clicks and things like that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在包含文本视图的视图中,覆盖 要返回的
hitTest:
方法自我
。然后鼠标事件将被发送到容器视图。警告:
我发现
hitTest:
将在窗口中任何地方的点击和鼠标跟踪事件中被调用,即使对于那些自然不会出现在窗口附近的事件也是如此。容器视图。如果窗口中有其他视图,您的hitTest:
方法会将容器视图变成一个黑洞,导致所有这些事件都被吸引到自身中,永远不会被任何其他视图看到。解决这个问题的方法是在吞下事件之前测试它是否在你的视野范围内。如果是,则返回
self
;如果不是,则返回nil
。最简单的方法是调用
super
的实现,如果该点位于视图内,它将返回视图或它本身的任何子视图,然后只返回self
如果该方法返回非nil
。如果它返回nil
,那么您也返回nil
。一种不太简单但可能更有效的方法是 将点从窗口坐标系转换为视图的,然后使用 NSPointInRect 来测试该点是否在视图的边界内。
In the view that contains the text view, override the
hitTest:
method to returnself
. The mouse events will then be sent to the container view.Caveat
I've since found that
hitTest:
will be called for click and mouse-tracking events anywhere in the window, even for events that wouldn't naturally be anywhere near the container view. If there are other views in the window, yourhitTest:
method will turn the container view into a black hole that causes all of those events to gravitate into itself, never to be seen by any other views.The fix for that is to test whether the event is within your view before swallowing it. If it is, return
self
; if it isn't, returnnil
.The simplest way to do that is to call
super
's implementation, which will return the view or any subview of itself if the point is within the view, and then just returnself
if that method returned non-nil
. If it returnednil
, then you returnnil
, too.A less-simple but possibly more efficient method would be to convert the point from the window's coordinate system to the view's, then use
NSPointInRect
to test whether the point is within the view'sbounds
.只是将 Peter 精彩的描述放入代码中:
Just to put Peter's fantastic description into code: