NSView 通过 NSTextView 接收点击事件

发布于 2024-11-30 14:14:49 字数 208 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉梦枕江山 2024-12-07 14:14:49

在包含文本视图的视图中,覆盖 要返回的 hitTest: 方法 自我。然后鼠标事件将被发送到容器视图。

警告:

我发现 hitTest: 将在窗口中任何地方的点击和鼠标跟踪事件中被调用,即使对于那些自然不会出现在窗口附近的事件也是如此。容器视图。如果窗口中有其他视图,您的 hitTest: 方法会将容器视图变成一个黑洞,导致所有这些事件都被吸引到自身中,永远不会被任何其他视图看到。

解决这个问题的方法是在吞下事件之前测试它是否在你的视野范围内。如果是,则返回self;如果不是,则返回nil

最简单的方法是调用 super 的实现,如果该点位于视图内,它将返回视图或它本身的任何子视图,然后只返回 self 如果该方法返回非nil。如果它返回 nil,那么您也返回 nil

一种不太简单但可能更有效的方法是 将点从窗口坐标系转换为视图的,然后使用 NSPointInRect 来测试该点是否在视图的边界内。

In the view that contains the text view, override the hitTest: method to return self. 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, your hitTest: 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, return nil.

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 return self if that method returned non-nil. If it returned nil, then you return nil, 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's bounds.

凉薄对峙 2024-12-07 14:14:49

只是将 Peter 精彩的描述放入代码中:

- (NSView *)hitTest:(NSPoint)aPoint
{
    NSView *result = [super hitTest:aPoint];
    if (result)
    {
        result = self;
    }
    return result;
}

Just to put Peter's fantastic description into code:

- (NSView *)hitTest:(NSPoint)aPoint
{
    NSView *result = [super hitTest:aPoint];
    if (result)
    {
        result = self;
    }
    return result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文