检查鼠标是否在 NSTableView 中被点击

check whether mouse was clicked inside NSTableView

我在 NSTableView 子类中有一些鼠标点击检查代码,可以拦截和修改鼠标事件以允许点击 table 内的按钮,但问题是这些事件也是如果在其他任何地方单击鼠标,而不仅仅是在 table 上,则会被拦截。因此,我的问题是:如何检查 NSPoint.locationInWindow 是否仅在 table 的 visible 范围内?

即使在 table 行滚动到可见 table 区域之外的某个地方单击,我下面的代码也会让事件通过。

class ButtonTableView : NSTableView
{
    var isAtForeground:Bool = false;

    override init(frame frameRect:NSRect) {
        super.init(frame: frameRect);
    }

    required init?(coder:NSCoder) {
        super.init(coder: coder);
        addEventInterception();
    }

    func addEventInterception() {
        NSEvent.addLocalMonitorForEventsMatchingMask(.LeftMouseDownMask, handler: {
            (theEvent) -> NSEvent! in

            /* Don't bother if the table view is not in the foreground! */
            if (!self.isAtForeground) { return theEvent; }

            var e:NSEvent? = theEvent;
            let p:NSPoint = theEvent.locationInWindow;

            // Check for click within table bounds
            let tableBoundsInWindowCoords:NSRect = self.convertRect(self.bounds, toView: nil);
            if (CGRectContainsPoint(tableBoundsInWindowCoords, p))
            {
                // This gets through even if clicked on table rows that are scrolled-out and not within the table's visible area!
            }
        });
    }
}

等等!没说什么!经过深思熟虑,我再次想通了……我不应该检查 table 视图的边界,而是检查其父视图 NSClipView 的边界!完全有道理,但可能不会立即显而易见。这解决了问题。