Whats the relation between First Responder and hitTest methods?

808 Views Asked by At

I understand how the system find the view handles touch events by calling the following methods on a view and its subviews

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;

But I don't understand the role of first responder in this mechanism.

Does firstResponder represents the start point of the hitTest traverse?

2

There are 2 best solutions below

6
Rui L On BEST ANSWER

I would recommend a complete reading of the first article

Using Responders and the Responder Chain to Handle Events

in Apple documentation

Touches, Presses, and Gestures

Short answer:

  1. Touch events are delivered directly to the first responder.

When your app receives an event, UIKit automatically directs that event to the most appropriate responder object, known as the first responder.

  1. First responder is determined by hit-testing.

UIKit uses view-based hit-testing to determine where touch events occur. Specifically, UIKit compares the touch location to the bounds of view objects in the view hierarchy. The hitTest(_:with:) method of UIView traverses the view hierarchy, looking for the deepest subview that contains the specified touch, which becomes the first responder for the touch event.

  1. If the first responder does not handle the event, the event is then passed from responder to responder in the active responder chain.
0
Chip Jarred On

There's not a lot of relationship between them, except that the result of hit test might cause the window to make the hit view become firstResponder.

firstResponder is all about keyboard events and, at least on macOS, menu item actions and commands like cut, copy, paste, undo etc...

When a keyboard event is received by the app from the Window Server, it goes to the firstResponder. If it's not interested in it, then it goes up the chain to nextResponder until it exhausts the responder chain. On macOS there are related but separate concepts of the mainWindow and keyWindow. They are usually the same, but can be different. If they are different the responder chain first starts with the keyWindow, and when that chain is exhausted, it then goes to the mainWindow. Then the application gets a crack at it. Then the application's delegate. Then if it's a document based app, the document and then the document's delegate.

On iOS, I'm a little fuzzy on the exact details, but it's similar. Actually I think it's simpler, because you don't have multiple windows.

Hit testing on the other hand is all about the view heirarchy. So the app finds which window (on macOS) the hit occurs in, then from there it proceeds down to it's immediate subviews, and then down its subviews, etc... until it finds a leaf view that is hit.