240
Monitoring
events and actions
In the previous chapter you learned how to create the basic view controllers that
fulfill the controller role of an MVC architectural model. You’re now ready to start
accepting user input, since you can now send users off to the correct object. Users
can interact with your program in two ways: by using the low-level event model or
by using event-driven actions. In this chapter, you’ll learn the difference between
the two types of interactions. Then we’ll look at notifications, a third way that your
program can learn about user actions.
Of these three models, it’s the events that provide the lowest-level detail (and
which ultimately underlie everything else), and so we’ll begin with events.
14.1 An introduction to events
We briefly touched on the basics of event management in chapter 10, but as we said
at the time, we wanted to put off a complete discussion until we could cover them
in depth; we’re now ready to tackle that job.
This chapter covers
■
The SDK’s event modeling
■
How events and actions differ
■
Creating simple event- and action-driven apps
241An introduction to events
Part 1 of this book, dealing with web design, outlined how events tend to work on
the iPhone. The fundamental unit of user input is the touch: a user puts his finger on
the screen. This could be built into a multi-touch or a gesture, but the touch remains
the building block on which everything else is constructed. It’s thus the basic unit that
we’re going to be examining in this chapter.
14.1.1 The responder chain
When a touch occurs in an SDK program, you have to worry
head, so when you’re building your hierarchies, they’ll be doing double duty.
Although figure 14.1 shows a direct connection from the first responder to the
window, there could be any number of objects in this gap in a real-world program.
Often the normal flow of the responder chain will be interrupted by delegation. A
specific object (usually a view) delegates another object (usually a view controller) to
act for it. We already saw this put to use in our table view in chapter 13, but we now
understand that a delegation occurs as part of the normal movement up the
responder chain.
If an event gets all the way up through the responder chain to the window and it
can’t deal with an event, then it moves up to the
UIApplication
itself, which most fre-
quently punts the event to its own delegate: the application delegate, an object that we’ve
been using in every program to date.
App
Delegate
The
Application
The
Window
First
Responder
Figure 14.1 Events on the
iPhone are initially sent to
the first responder, but then
travel up the responder chain
until someone accepts them.
242 CHAPTER 14 Monitoring events and actions
Ultimately you, the programmer, will be the person who decides what in the re-
sponder chain will respond to events in your program. You should keep two factors in
touch events). Let’s lead off with a more in-depth look at each.
First responders and keyboards
Before we leave this topic of responders behind, we’d like to mention that the first
responder is a very important concept. Because this first responder is the object that
can accept input, it’ll sometimes take a special action to show its readiness for input.
This is particularly true for text objects like
UITextField
and
UITextView
, which (if
editable) will pop up a keyboard when they become the first responder. This has two
immediate consequences.
If you want to pop up a keyboard for the text object, you can do so by turning it into
the first responder:
[myText becomeFirstResponder];
Similarly, if you want to get rid of a keyboard, you must tell your text object to stop
being the first responder:
[myText resignFirstResponder];
We’ll discuss these ideas more when we encounter our first editable text object to-
ward the end of this chapter.
243An introduction to events
UITOUCH REFERENCE
A
UITouch
object is created when a finger is placed on the screen, moves on the
screen, or is removed from the screen. A handful of properties and instance methods
can give you additional information on the touch, as detailed in table 14.1.
Together the methods and properties shown in table 14.1 offer considerable informa-
tion on a touch, including when and how it occurred.
Only the
described in table 14.2.
Table 14.1 Additional properties and methods can tell you precisely what happened during a touch event.
Method or property Type Summary
phase
Property Returns a touch phase constant, which indicates
whether touch began, moved, ended, or was canceled
tapCount
Property The number of times the screen was tapped
timestamp
Property When the touch occurred or changed
view
Property The view where the touch began
window
Property The window where the touch began
locationInView:
Method Gives the current location of the touch in the specified
view
previousLocationInView:
Method Gives the previous location of the touch in the specified
view
UITouch
phase:
UITouchPhaseBegan
locationInView:
(10,15)
UITouch
phase:
UITouchPhaseEnded
locationInView:
(28,32)
Each of these methods has two arguments: an
NSSet
of touches that occurred during
the phase in question and a
UIEvent
that provides a link to the entire event’s worth of
touches. You can choose to access either one, as you prefer; as we’ve said, we’re going
to be playing with the bare touches. With that said, we’re now ready to dive into an
actual example that demonstrates how to capture touches in a real-life program.
14.2 A touching example: the event reporter
Our sample application for events is something we call the event reporter, which will
offer a variety of responses depending on how and when the iPhone screen is
touched. We have two goals with our sample program.
Table 14.2 The encapsulating event object has a number of methods and properties
that let you access its data.
Method or property Type Summary
timestamp
Property The time of the event
allTouches
Method All event touches associated with the receiver
touchesForView:
Method All event touches associated with a view
touchesForWindow:
Method All event touches associated with a window
Table 14.3 The
UIResponder methods are the heart of capturing events.
Method Summary
touchesBegan:withEvent: Reports UITouchPhaseBegan events, for when fingers
touch the screen
lie beneath the view controller in the view hier-
archy, you call up the view controller’s own
.xib file, eventreporterViewController.xib. As
usual, you’ll add your new objects to the Main
Display window that represents the view con-
troller’s view.
All of your work in Interface Builder is, of
course, graphical, so we can’t show the code
of this programming process. However, we
have included a quick summary of the actions
you should take. The results are shown in fig-
ure 14.3.
■
Set the background color of the
UIView
to an attractive aluminum color. You do
this on the Attributes tab of the Inspector window, as you would with most of
your work in this project.
■
Create a
UILabel
, stretch it across the bottom of the screen, and set the color to
be steel. Also, clear out its text so that it doesn’t display anything at startup.
■
Create two
UITextField
s. This class of objects is generally used to accept input,
but we opted to use the objects for our pure display purposes because we liked
their look. (Don’t worry; we’ll show how to use the full functionality of a
UIText-
The tricky thing here is that the view controller doesn’t seem to appear in our
eventreporterViewController.xib file—at least not by that name. Fortunately, there’s a
proxy for it. Since the view controller is what loads up the .xib, it appears as the file’s
owner in the nib document window. You can therefore connect objects to the view
controller by linking them to the file’s owner proxy. This is a common situation, since
view controllers frequently load additional .xib files for you.
Listing 14.1 shows your view controller’s header file, eventreportViewController.h,
following the addition of these
IBOutlet
s. The listing also contains a declaration of a
method that you’ll use later in this project.
@interface eventreporterViewController : UIViewController {
IBOutlet UITextField *startField;
IBOutlet UITextField *endField;
IBOutlet UILabel *bottomLabel;
}
- (void)manageTouches:(NSSet *)touches;
@end
To finish up this process, you connect your Interface Builder objects to the
IBOutlet
s,
using the procedures described in chapter 12.
14.2.2 Preparing a view for touches
Touch events can only be captured by UIView objects. Unfortunately, as of this writing,
there’s no way to automatically delegate those touches to a view controller. Therefore,
in order to manage touch events using the MVC model, you’ll typically need to sub-
class a
UIView, capture the events there, and then send messages to the view control-
ler.
In your project you’ll create a new object class,
[self.nextResponder manageTouches:touches];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.nextResponder manageTouches:touches];
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self.nextResponder manageTouches:touches];
}
The code in listing 14.2 is pretty simple. You’re just filling in standard methods so that
your program will have the responses you want when those messages are sent. The
overall structure of these methods reminds us of several important facts about events.
First, as promised, there are a variety of responder methods. Each of them reports
only the events for their specific phase. So, for example, the
touchesBegan:with-
Event:
method would only have
UITouchPhaseBegan
touches in it. In forwarding on
these touches we could have kept the different phases distinct, but we’ve instead
decided to throw everything together and sort it out on our own on the other side.
Second, we’ll comment one final time that these methods send us two pieces of
information: a set of touches and an event. They are partially redundant, and which
one you work with will probably depend on the work you’re doing. If you’re not doing
complex multi-touch events, then the
NSSet
of touches will probably be sufficient.
Third, note that you’re sending the touches to the view controller by way of the
nextResponder
method. As you’ll recall, the responder chain is the opposite of the
view hierarchy at its lower levels, which means in this case the
discussion of events.
AN ASIDE ON THE TEXT FIELDS AND LABEL
If you were to actually code in this example, you’d discover that this program correctly
responds to touch events even when the touches occurred atop one of the text fields
or the label at the bottom of the page. How does your program manage that when you
only built event response into the
reportView
?
The answer is this: it uses the responder chain. The text fields and the label don’t
respond to the event methods themselves. As a result, the events get passed up the
responder chain to the
reportView
, which does leap on those events, using the code
we’ve just seen.
14.2.3 Controlling your events
Intercepting touches and forwarding them up to the view controller may be the
toughest part of this code. Once the events get to the view controller, they run
through a simple method called
manageTouches:
, as shown in listing 14.3.
::eventreporterViewController.m::
- (void)manageTouches:(NSSet *)touches {
for (UITouch *touch in touches) {
if (touch.phase == UITouchPhaseBegan) {
CGPoint touchPos = [touch locationInView:self.view];
startField.center = touchPos;
startField.text = [NSString stringWithFormat:
@"Begin: %3.0f,%3.0f",touchPos.x,touchPos.y];
} else if (touch.phase == UITouchPhaseMoved) {
bottomLabel.text = @"Touch is moving ";
B
C
D
E
C
C
F
249A touching example: the event reporter
Once you get a touch, the first thing you do is determine what phase it arrived in.
Originally you could have determined this information based on which method a
touch arrived through, but since we combined everything you have to fall back on the
phase
property. Fortunately, it’s easy to use. You just match it up to one of three con-
stants
C
, and that determines which individual actions your program undertakes.
Having different responses based on the phase in which a touch arrive is com-
mon—which is in fact why the event methods are split up in the first place. Our exam-
ple demonstrates this with some distinct responses: you move your start field when
touches begin, you move your end field when touches end, and you update the bot-
tom label in both the moved and ended phases.
In your
UITouchPhaseBegan
response, you delve further into your touch’s data by
using the
locationInView:
method to figure out the precise coordinates where a
touch occurred
D
. You’re then able to use that data to reposition your text field and
s. It was tempting to
process events in the
reportView
itself, especially since
you had to create a subclass anyway, but instead you
pushed the events up to the view controller, and in
doing so revealed why you’d want to do
MVC modeling.
Since it takes on the controller role, you gave the
view controller access to all of its individual objects,
and therefore you didn’t have to try to remember
what object knew about what other object. Tying
things into the view controller, rather than scattering
them randomly across your code, made your project
that much more readable and reusable, which is what
most architectural and design patterns are about.
Figure 14.5 Your event responder
uses a few graphical elements to
report events as they occur.
250 CHAPTER 14 Monitoring events and actions
14.3 Other event functionality
Before we complete our discussion of events entirely, we’d like to cover a few more
topics of interest. We’re going to explore how to regulate the report of events in a vari-
ety of ways and then describe some deficiencies in the event model.
14.3.1 Regulating events
As we mentioned earlier, there are some ways that you can modify how events are
reported (and whether they are at all). As you’ll see, three different objects give you
access to this sort of regulation:
UIResponder
,
Returns the next responder in
the chain by default but can be
modified
hitTest:withEvent: UIView
method
Returns the deepest subview con-
taining a point by default but can
be modified
exclusiveTouch UIView
property
A Boolean set to NO by default;
controls whether other views in
the same window are blocked
from receiving events
multipleTouchEnabled UIView
property
A Boolean set to NO by default;
controls whether multi-touches
after the first are thrown out
beginIgnoringInteractionEvents UIApplication
method
Turns off touch event handling
endIgnoringInteractionEvents UIApplication
method
Turns on touch event handling
isIgnoringInteractionEvents UIApplication
method
Tells whether the application is
ignoring touch events
251Other event functionality
class methods, you can take the opposite approach by
overriding
hitTest:withEvent:
. This method is passed a
CGPoint
and an event, and
by default it returns the deepest subview that contains the point. By writing a new
method, you can cause your responder chain to start at a different point.
The two
UIView
properties that we noted both work as you’d expect.
exclusive-
Touch
declares that the view in question is the only one that can receive events (which
is an alternative way that we could have managed our eventreporter example, where
we didn’t want anything but the
reportView
to accept events). Meanwhile,
multiple-
TouchEnabled
starts reporting of multi-touch events, which are otherwise ignored.
UIAPPLICATION REGULATION
Finally we come to the
UIApplication
methods. These lie outside of our normal hier-
archy of objects, and thus we can’t get to them from our view objects. Instead we need
to call them directly from the
UIApplication
object as shown here:
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
developers—such as programmers creating games and novelties—who might need
access to multi-touches and more complex gestures.
14.4 An introduction to actions
So if you’re not usually going to be programming directly with events, how will you
access user input? The answer is by using actions. You’ll typically depend on preexist-
ing text views, buttons, and other widgets to run your programs. When using these
objects, you don’t have to worry about raw events at all. Instead, you can build your
programs around control events and actions that are generated by
UIControl
s.
14.4.1 The UIControl object
When we were working with events, we found that the
UIResponder
class held many of
the methods critical for event control. Similarly, we can access a lot of the methods
important to
SDK controls through the
UIControl
class.
UIControl
is a child of
UIView
(and thus
UIResponder
). It is the parent of important
user interface controls such as
UIButton
,
UISwitch
,
continueTrackingWithTouch:withEvent:
, and
endTracking-
WithTouch:withEvent:
, methods that work in a similar way to the event response func-
tions that we played with in
UIResponder
. But we won’t be using these methods at all,
because they don’t represent the simple advantages that you’ll see when using control
objects. For that, we turn to
UIControl
’s action-target mechanism.
14.4.2 Control events and actions
The
UIControl
object introduces a whole new event-handling infrastructure that
takes touch events of the sort that we might have directly handled in the previous sec-
tion and (eventually) converts them into simple actions, without you having to worry
about the specifics of how a user accessed your control. The complete sequence of
events is outlined in figure 14.6.
When a touch event arrives at a
UIControl
object (via normal dispatching along
the responder chain), the control does something unique. Inside the standard
253An introduction to actions
UIResponder
methods that we used in the previous section (such as
touches-
Began:withEvent:
UIControlEventTouchDragOutside
A finger movement ending just outside the control.
UIControlEventTouchDragEnter
A finger movement that enters the control.
UIControlEventTouchDragExit
A finger movement that exits the control.
UIControlEventTouchUpInside
A finger removed from the screen inside the control.
UIControlEventTouchUpOutside
A finger removed from the screen outside the control.
UIControlEventTouchCancel
A system event canceled a touch.
UIControlEventValueChanged
A slider (or other similar) object changed its value.
UIControlEventEditingDidBegin Editing began in a UITextField.
UIControlEventEditingChanged Editing changed in a UITextField.
touch
events
sendActionsForControlEvents:
UIResponder
methods
sendAction:to:forEvent:
UIControl
sendAction:to:fromSender:forEvent:
UIApplication
target or
responder
chain
Figure 14.6
UIControl
That whole process can be slightly exhausting, and fortunately you shouldn’t nor-
mally need to know its details. For your purposes, you should be aware that a
UIControl
object turns a touch event first into a control event and then into an action with a specific
recipient. Even better, it’s only the last part of that conversion, from control event into
targeted action, that you need to code.
14.4.3 The addTarget:action:forControlEvents: method
A
UIControl
object maintains an internal dispatch table that correlates control events
with target-action pairs. In other words, this table says which method should be run by
which object when a specified event occurs. You can add entries to this table with the
UIControl
object’s
addTarget:action:forControlEvents:
method. The following
example shows how it works:
[controlObject addTarget:recipientObject action:@selector(method)
forControlEvents:UIControlEvents];
The first argument,
addTarget:
, says who the message will be sent to. It’s frequently
set to
self
, which usually refers to a view controller that instantiated the control
object.
The second argument,
action:
, is the trickiest. First, note that it uses the
@selec-
With all these puzzle pieces in place, you’re now ready to write some code that will
make actual use of actions (and this method). As a simple example, you’re going to
expand the functionality to your event reporter by adding a “reset” button.
14.5 Adding a button to an application
The simplest use of an action is probably just adding a button to an application and
then responding to the press of that button. As we’ll see, this turns out to be a lot eas-
ier than digging through individual touches.
We’ve opted to show you how to work with a button in two ways: first by using the
addTarget:action:forControlEvents:
method that we were just introduced to and
then by using Interface Builder’s
IBAction
declaration.
Both of these examples begin with your existing eventreporter program. You’ll add
a simple
UIButton
to it using Interface Builder. Place the button down atop the label at
the bottom of our page and use the
attributes
tag to label it “Reset.” With it in place
and defined, it’s now ready to be linked into your program by one of two different ways.
Both examples will call a method you’ve written called
resetPage:
, which just
restores the three changeable objects in your eventreporter to their default states. It’s
shown in listing 14.4 of
eventreporterViewController.m
, and as you can see is
entirely elementary.
- (void)resetPage:(id)sender {
viewDidLoad
method (if you created the controller in Interface Builder).
Listing 14.5 shows what the
viewDidLoad
method of your view controller looks like
when applied to a button called
myButton
.
- (void)viewDidLoad {
[myButton addTarget:self action:@selector(resetPage:)
forControlEvents:UIControlEventTouchUpInside];
[super viewDidLoad];
}
This real-life example of
addTarget:action:forControlEvents:
looks much like the
sample we showed in the previous section. You’re sending a message to your button
that tells it to send the view controller a
resetPage:
message when a user takes his or
her finger off the screen while touching the button.
That single line of code is all that’s required; from there on out, your button will
connect to your
resetPage:
method whenever it’s pushed (and released).
14.5.2 Using an IBAction
The other way that you can link up actions to methods is to do everything inside of
Interface Builder. This is the preferred choice if you’ve already created your object in
Interface Builder (as we’ve suggested) and you’re not planning to change its behavior
in runtime.
possible
IBAction
s to which you could link your control event.
To our eyes, the results are almost magical. With that single graphical link, you’ve
replaced the
addTarget:action:forControlEvents:
call and in fact any code of any
type. The button now links to the targeted action “automagically.”
What we’ve described so far covers the broad strokes of actions; everything else lies
in the details. If we spent less time on actions than events, it’s not because actions are
less important than events, but because they’re a lot simpler.
From here on, your challenge in using controls will simply be in figuring out how
individual controls work. See appendix A for an overview of classes and the Apple
Class References for specifics. However, there are a few controls that we’d like to give
more attention to because they vary a bit from the norm.
14.6 Other action functionality
In this section we’ll look at two controls that report back different signals than the
simple button-up or button-down control events. The first is the
UITextField
, the
prime control for entering text, and the second is the relatively simple (but unique)
UISlider
. In the process we’ll also explore the other text-based entry formats, since
they share some unique issues with
UITextField
.
14.6.1 The UITextField
There are four ways to display pure text in the SDK: the
UILabel
, the
UITextField
would accept user input. It’s intended to be used mainly for
accepting short user input. The trickiest thing about using a
UITextField
is getting it
to relinquish control of your iPhone after you call up a keyboard. Listing 14.6 shows
the two steps needed to resolve this problem. We’re assuming that you’re working
with a
myText UITextField
object created inside Interface Builder and instantiated
inside a view controller.
- (void)viewDidLoad {
myText.returnKeyType = UIReturnKeyDone;
[super viewDidLoad];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
Your setup of an Interface Builder object begins, pretty typically, inside its controller’s
viewDidLoad
method. Here you turn the text field’s keyboard’s Return key into a
bright blue “Done” key
B
, to make it clear that’s how you get out. You accomplish this
by using part of the
UITextInputTraits
protocol, which defines a couple of common
features for objects that use keyboards.
To do anything else, you need to declare a delegate for the
D
259Other action functionality
special control events (especially
UIControlEventEditingDidEnd
) and also look at
its
text
property.
In a moment we’re going to provide a sample of how that works, but first let’s
examine a few other text objects that aren’t controls but that you might use to accept
text entry.
UILABEL
The
UILabel
is not user-editable.
UISEARCHBAR
The
UISearchBar
looks an awful lot like a
UITextField
with some nuances, such as a
button to clear the field and a bookmark button. Despite the similarities in style,
the
UISearchBar
is not a
UIControl
object, but instead follows an entirely differ-
ent methodology.
To use a
UISearchBar
delegate
property; then you
can watch for delegate messages, most importantly
textViewDidEndEditing:
. There’s
an example of a text view in usage in chapter 16, section 16.3.4.
With our quick digression into this variety of text objects out of the way, we can
now return to the other
UIControl
object that we wanted to discuss:
UISlider
.
14.6.2 The UISlider
The slider is a simple object, but we’ve singled it out because it’s the one other class
that has its own control event,
UIControlEventValueChanged
. If you target this event,
you’ll find that it gets called whenever the slider moves, but the control event won’t
tell you what the new value is. To get that information, your action method must query
the slider’s properties.
There are three properties of particular note:
value
shows a slider’s current value,
minimumValue
shows the bottom of its scale, and
maximumValue
shows the top of its
scale. You can use the
value
without modification if you’ve set your slider to return a
changeColor:
. Whenever either control is changed, this method adjusts the color of
the screen accordingly. Listing 14.7 shows how.
- (IBAction)changeColor:(id)sender {
int red; int green; int blue;
if ([myText.text caseInsensitiveCompare:@"red"]
== NSOrderedSame) {
red = 1; green = 0; blue = 0;
} else if ([myText.text caseInsensitiveCompare:@"blue"]
== NSOrderedSame) {
red = 0; green = 0; blue = 1;
} else if ([myText.text caseInsensitiveCompare:@"green"]
== NSOrderedSame) {
red = 0; green = 1; blue = 0;
} else {
red = .5; green = .5; blue = .5;
}
float newShade = mySlider.value /
(mySlider.maximumValue - mySlider.minimumValue);
[self.view setBackgroundColor:
[UIColor colorWithRed:red green:green blue:blue alpha:newShade]];
}
The hardest part of working with a
UITextField
is setting it up, which you did in list-
ing 14.6. Now that you’ve got input coming back, all you need to do is access the
text
property and do with it as you will
B
.
ment by letting multiple controls point to a single
method, a technique that will be useful in more com-
plex programs.
As usual, there’s more information on both of these
controls in the Apple class references, including lots of
methods and properties that we didn’t talk about.
14.6.4 Actions made easy
Throughout the latter half of this chapter we’ve seen
controls that were tied to the fully fledged target-
action mechanism. In the next chapter, that’s going
to change a bit when we see the same idea in a some-
what simplified form.
Sometimes buttons or other controls are built into other classes of objects (such as
the button that can be built into the navigation bar). These controls will have special
methods that allow them to automatically create a target-action pair. As a result, you
don’t have to go through the nuisance of calling the
addTarget:action:forControl-
Events:
method separately.
We’ll point this technique out when we encounter it as part of the navigation
controller.
14.6.5 Actions in use
There are numerous control objects that we’ve opted not to cover here, mainly
because they use the same general principles as those we’ve already talked about.
Nonetheless, they’ll remain an important factor throughout the rest of this book.
In particular, controls represent one of the main ways that users can offer input to
your programs, and we’ll discuss them when we talk about data in chapter 16. We’ll
also be offering more complex programs that use a variety of controls from chapter 16
on. Through those examples, the majority of the
UI controls will receive some cover-
selector:
is the method that will be called in the
observer, the
name:
is the name of the notification (which will be in the class refer-
ence), and the
object:
can be used if you want to restrict which objects you receive
notification from (but it is usually set to
nil
).
For example, to receive the
UIDeviceOrientationDidChangeNotification
notifi-
cation that we’re going to talk about in chapter 17, you might use the following code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceDidRotate:)
name:@"UIDeviceOrientationDidChangeNotification" object:nil];
Overall, notification programming tends to have four steps. First, you learn that
there’s a notification by reading the appropriate class reference (
UIDevice
in this
case). Second, you may need to explicitly turn on the notification (as is indeed the
case for
UIDeviceOrientationDidChangeNotification
). Third, you write a method
that will respond to the notification (in this case,
deviceDidRotate:
). Fourth, you
connect up the notification to the method with the
ple screens of content.
That’s going to be the basis of our next chapter.