Mike Lischke
Mike Lischke

Reputation: 53492

How do get an NSView from a given location

Given a screen position (e.g. during a drag operation) how would I find the view that's at that position in my application?

Converting the coordinates to window or source view coordinates is simple, but I can't find any routine to get a view from the given location. Is there any other solution than enumerating through all child views/windows recursively?

Please take this a bit further than just NSView's hitTest: message (which is a good answer). Is there a generic message to get the deepest view at a given position regardless of nested window hierarchies (without manually iterating all windows)?

Upvotes: 2

Views: 846

Answers (3)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

First of all you should rarely need it. The concept of "finding a view for an user interaction" is the responder chain. So, if a subview should respond to drag operation, simply add drag & drop capability to that view(s).

If you simply need the deepest hit on a view for that coordinate you can use -hitTest (NSView). Going up to your root view, you will find the parent views. If you have overlapping views, it becomes more complex. Please add that information to your question.

Upvotes: 1

Steveo
Steveo

Reputation: 2268

You'll want to call -[NSView hitTest:] and it will return the view, if any, containing the point in question. The receiving view should be your root view (such as the NSWindow's contentView) and the point should be converted to that view's superview's coordinates.

Upvotes: 2

JDS
JDS

Reputation: 1203

You can use NSView's hitTest: method:

Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point, or nil if that point lies completely outside the receiver.

[[window contentView] hitTest:aPoint]

But the aPoint has to be in the superview's coordinate system:

Parameters
aPoint
A point that is in the coordinate system of the receiver’s superview, not of the receiver itself.

Upvotes: 2

Related Questions