iosuikitfirst-responderuiresponder

What is first responder?


According to Apple's documentation:

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

Same documentation explain how first responder is determined:

The hitTest:withEvent: 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.

What I don't understand is why there is a property of UIResponder called isFirstResponder? And why becomeFirstResponder exists. Should not the first responder be determined dynamically by UIKit based on location of the specific touch event?

Additionally, canBecomeFirstResponder return NO for UIView, which is clearly incorrect since views do handle touch events.

The only way I can think that can resolve this confusion is if all these methods are relevant only to events of the type of shake, remote control and editing menu. But the documentation is not clear about it.


Solution

  • What I don't understand is why there is a property of UIResponder called firstResponder?

    There isn't. UIResponder does not have a public property named firstResponder.

    And why becomeFirstResponder exists.

    The main use of becomeFirstResponder is to programmatically choose which text field gets keyboard events.

    Should not the first responder be determined dynamically by UIKit based on location of the specific touch event?

    There are more kinds of events than touch events. For example, there are keyboard events and motion events. The first responder tracked by UIKit is for non-touch events. In other systems, this concept is usually called the “focus” or more specifically the “keyboard focus”. But (in iOS) the first responder can be a view that doesn't respond to keyboard events.

    Additionally, canBecomeFirstResponder return NO for UIView, which is clearly incorrect since views do handle touch events.

    That's ok, because touch events don't really start at the first responder. They start at the view returned by -[UIView hitTest:withEvent:].

    The only way I can think that can resolve this confusion is if all these methods are relevant only to events of the type of shake, remote control and editing menu. But the documentation is not clear about it.

    There are more kinds of non-touch events that start with the first responder, but aside from that, you have resolved it correctly.