Game Development Reference
In-Depth Information
touch-related tasks. The last technique is to wire up one of the six
UIGestureRecognizer
classes to
a
UIView
and register an object to respond to the different gestures.
I think the last technique is the most robust in most cases, because it provides a way for users to
interact with your application using a set of known gestures. However, there are perfectly good
reasons to use the second technique, implementing the touch-related tasks, especially if the user
interaction you are shooting for is not a gesture per se. An example might be a drawing application,
where you simply want access to all points of contact on the screen to do your drawing.
The following section will review the touch-related tasks of
UIView
. We will then move on and
explore
UIGestureRecognizer
classes and motion events.
The sample code that accompanies this chapter is found in the project Sample 08. While most of
the code in this topic can be run on either a device or the emulator, I highly recommend running this
iPhone
(or iPod touch)—if possible,
iOS
4.2 or later—because the complex gestures are
UIView
to Receive Touch Events
has four tasks that get called when a user touches it on the screen. I am collectively calling
The four touch-related tasks
-(void)touchesBegan:withEvent:
-(void)touchesCancelled:withEvent:
-(void)touchesEnded:withEvent:
-(void)touchesMoved:withEvent:
The first argument of each of these tasks is an
NSSet
that contains a
UITouch
for each discrete touch
on the screen. The second argument is a
UIEvent
that is basically a generic wrapper for the three
different input types available on
iOS
: touch events, motion events, and remote-control events.
We won't be covering remote-control events; those are events generated by accessories, like an
external keyboard.
The task
touchesBegan:withEvent
: is called as soon as a finger (or fingers) touch the screen. The
task
touchesEnded:withEvent
: is called when the fingers are removed. If the fingers slide around,
the
touchesMoved:withEvent
: would be called. The task
touchesCancelled:withEvent
: is called if
the system has to take control of the screen. For example, if another application is launched, the
touchesCancelled:withEvent
: is called on the first application before control is passed to the new
app. The sample code provides an example of using these tasks, as shown in Figure
8-1
.