Basics of User Interface Events in iOS Apps
User interface (UI) events in iOS are the result of (finger) touches on a view (or of the user shaking the device). A UITouch object representing each touch is packaged in the event sent to the responder. This object contains information such as the view being touched, the location of the touch, a timestamp, and a phase.
The phase is necessary because a touch object goes through a sequence of phases during a touch — in the following order:
UITouchPhaseBegan: Finger touched a view.
UITouchPhaseMoved: Finger moved on that view or moved to an adjacent view.
UITouchPhaseEnded: Finger lifted from a view.
Via the main event loop, the application object receives touch events in its event queue. It then packages them as UITouch objects within UIEvent objects and dispatches them to the appropriate responder. In order for the responder to handle events, it must override four methods (declared in the UIResponder base class), as follows:
touchesBegan is called for touches in the Began phase.
touchesMoved is called for touch objects in the Moved phase. That is, after the touch, the user’s finger continues to press while dragging on the screen.
touchesEnded is called for touch objects in the Ended phase. That is, the user lifts her finger after the touch.
touchesCancelled is called when (say) an incoming phone call cancels touch events that took place before the phone call.
The figure below shows how touches and events are handled in iOS.
Certain specialized UI elements (like text fields) use a different mechanism for user-interface interactions. Rather than reporting events to their responders, who then have to decide how to act on these events, the UI elements send actions (or action messages) to their responders that these responders act upon.
The information stored in an action message consists of two items: a selector, which identifies the method to be invoked, and a target, which is the object that receives the message. A method that will handle an action message must look like the following:
All this may sound complicated, but just note that delegation is the common theme in handling events. Essentially, events and actions are recognized in views and then handling of the event or action is delegated to a responder. Keep in mind that delegation needs to be specified differently in different UI elements, and figuring out how to develop an iOS UI will be a breeze.