0
votes

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 controller 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.

2
I’m not sure I understand why you say ‘self.view is null’ (a non-existent view cannot be added to a window) and what do you mean by top level window (a view belongs to a single window). - user557219

2 Answers

1
votes

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];
-1
votes

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
    }
}