Graphics Programs Reference
In-Depth Information
UIDevice Notifications
One object that regularly posts notifications is
UIDevice
. Here are the constants that
serve as names of the notifications that a
UIDevice
posts:
UIDeviceOrientationDidChangeNotification
UIDeviceBatteryStateDidChangeNotification
UIDeviceBatteryLevelDidChangeNotification
UIDeviceProximityStateDidChangeNotification
Wouldn't it be cool to get a message when the device rotates? Or when the phone is placed
next to the user's face? These notifications do just that.
Create a new
Empty Application
project and name it
HeavyRotation
. Enter
Rotation
into
the
Class Prefix
field, enter
iPhone
for the device family, and only check the box for
Use
Automatic Reference Counting
.
In
RotationAppDelegate.m
, register to receive notifications when the orientation of
the device changes:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
// Get the device object
UIDevice *device = [UIDevice currentDevice];
// Tell it to start monitoring the accelerometer for orientation
[device beginGeneratingDeviceOrientationNotifications];
// Get the notification center for the app
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
// Add yourself as an observer
[nc addObserver:self
selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:device];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Now, whenever the device's orientation changes, the message
orientationChanged:
will be sent to the instance of
RotationAppDelegate
. In the same file, add an
ori-
entationChanged:
method:
- (void)orientationChanged:(NSNotification *)note
{