开发者

Getting mouse position from a custom nsview

I'm trying to get the mouse location relative to the nsview.

There are at least two methods that I know of:

NSPoint mousePosition = [self.window convertScreenToBase:[NSEvent mouseLocation]];

And

NSPoint mousePosition = [self.window mouseLocationOutsideOfEventStream];

The problem with both of those methods is that self.view is null. I'm adding this view from a view control开发者_Go百科ler that itself was added by another view controller. I would like to know if it's possible to get the toplevel window starting from a nsview that can be many levels below.

Edit: of course I can use:

NSWindow *window = [self valueForKeyPath:@"delegate.delegate.view.window"];

But there must be a better way.


I would like to know if it's possible to get the toplevel window starting from a nsview that can be many levels below.

Sure:

NSView *view = …;
NSWindow *window = [view window];


EDIT: the following is not necessary, as pointed out in the comments, view.window will return the window (if any) from anywhere in the hierarchy.

This question is quite old, but if anyone ends up here looking up if it's possible to get the toplevel window starting from a nsview that can be many levels below.

I came up with this in Swift 4:

extension NSView {

    /// Returns the first window referenced by self or any of the parent views in the hierarchy
    var parentWindow: NSWindow? {
        if self.window != nil {
            return self.window
        }
        return self.superview?.parentWindow
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜