1. Trang chủ
  2. » Công Nghệ Thông Tin

Praise for The iPhone Developer’s Cookbook 2nd phần 6 pptx

88 357 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 88
Dung lượng 11,45 MB

Nội dung

ptg 411 Recipe: Tappable Overlays } - (void) action: (id) sender { // Add the subview [self.view.window addSubview:self.overlay]; // Start the activity indicator [(UIActivityIndicatorView *)[self.overlay viewWithTag:202] startAnimating]; // Call the finish method, on delay [self performSelector:@selector(finish) withObject:nil afterDelay:3.0f]; } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. Recipe: Tappable Overlays Use custom overlays to present information as well as to establish modal sequences. Recipe 10-9 creates a custom class called TappableOverlay.When tapped, this view removes itself from the screen.This behavior makes it particularly suitable for showing information in a way normally reserved for the UIAlertView class. To use this class, create a view instance in Interface Builder.Add as many subviews and design elements as needed. Use File > Read Class Files to import the TappableOverlay.h header file.Then change the view class from UIView to TappableOverlay using the Iden- tity Inspector (Command-4) and save the project. To present the view, add it to the window just as Recipe 10-8 did. - (void) action: (id) sender { // Add the overlay [self.view.window addSubview:self.overlay]; } No further programming is needed.The view waits for a user tap and when one is received, it removes itself from the window. Figure 10-8 shows a simple example of this kind of overlay; it displays “Tap to Con- tinue.” It’s easy to see how you can extend this concept to show any kind of pertinent information, creating a custom alternative to the UIAlertView class.As with Recipe 10-8, this example does not use any orientation awareness. ptg 412 Chapter 10 Alerting Users Figure 10-8 This simple overlay dismisses itself on receiving a user touch. Recipe 10-9 Building a Custom Dismissible Alert View That Responds to User Taps @interface TappableOverlay : UIView @end @implementation TappableOverlay - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // Remove this view when it is touched [self removeFromSuperview]; } @end Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. Recipe: Orientable Scroll-Down Alerts You can extend the modal concepts introduced in Recipe 10-8 to create a noninteractive overlay that acts as a backdrop for a scroll-down alert. In Recipe 10-10, that overlay hosts a view with an embedded button as shown in Figure 10-9.This view is presented and ptg 413 Recipe: Orientable Scroll-Down Alerts Figure 10-9 This modally presented message scrolls down into view and is dismissed by tapping the OKAY button. dismissed via a pair of simple UIView animation blocks; the OKAY button triggers the dismiss: method that scrolls the view offscreen. The message view was created in Interface Builder as a standard UIView. It’s added to the overlay as a subview in the viewDidLoad method. Rather than adding and removing the overlay from the main window, as Recipe 10-8 did, this recipe uses the overlay’s alpha property to hide and show itself. Unlike the previous two recipes, this recipe does pay attention to screen orientation. It adapts its size and presentation to match the current iPhone orientation. It accomplishes this in two ways. First, it applies an affine transform to the overlay when the orientation changes. Second, it adjusts the overlay and message view frames before presentation, matching the shape of the current window. Although this example scrolls in from the top of the screen, it’s trivial to adapt the math to have it scroll in from the sides (use the x origin rather than the y origin) or bot- tom (add 320 or 480 to the view height).Alternatively, you might center the view and animate its size so that it pops rather than slides into view. Recipe 10-10 Creating an Orientable Scroll-Down Overlay - (void) dismiss: (id) sender { ptg 414 Chapter 10 Alerting Users // Animate the message view away [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3f]; [UIView setAnimationCurve:UIViewAnimationCurveLinear]; mvframe.origin = CGPointMake(0.0f, -300.0f); self.messageView.frame = mvframe; [UIView commitAnimations]; // Hide the overlay [self.overlay performSelector:@selector(setAlpha) withObject:nil afterDelay:0.3f]; } - (void) action: (id) sender { // Adjust the overlay sizes based on the screen orientation self.overlay.frame = self.view.window.frame; mvframe.size.width = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? 320.0f : 480.0f; mvframe.origin = CGPointMake(0.0f, -mvframe.size.height); self.messageView.frame = mvframe; // Show the overlay if (!self.overlay.superview) [self.view.window addSubview:self.overlay]; self.overlay.alpha = 1.0f; // Animate the message view into place [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3f]; [UIView setAnimationCurve:UIViewAnimationCurveLinear]; mvframe.origin = CGPointMake(0.0f, 20.0f); self.messageView.frame = mvframe; [UIView commitAnimations]; } - (void) viewDidLoad { self.navigationItem.rightBarButtonItem = BARBUTTON(@"Action", @selector(action)); // Initialize the overlay and message view self.overlay.alpha = 0.0f; [self.overlay addSubview:self.messageView]; mvframe = messageView.frame; mvframe.origin = CGPointMake(0.0f, -300.0f); self.messageView.frame = mvframe; ptg 415 Recipe: Using the Network Activity Indicator Figure 10-10 The network activity indicator is controlled by a UIApplication property. } - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { // Apply overlay transforms based on the orientation if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) self.overlay.transform = CGAffineTransformMakeRotation(M_PI); else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) self.overlay.transform = CGAffineTransformMakeRotation(-M_PI / 2.0f); else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) self.overlay.transform = CGAffineTransformMakeRotation(M_PI / 2.0f); else self.overlay.transform = CGAffineTransformIdentity; return YES; } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. Recipe: Using the Network Activity Indicator When your application accesses the Internet from behind the scenes, it’s polite to let your user know what’s going on. Rather than create a full-screen alert, Cocoa Touch provides a simple application property that controls a spinning network activity indicator in the sta- tus bar. Figure 10-10 shows this indicator in action, to the right of the WiFi indicator and to the left of the current time display. Recipe 10-11 demonstrates how to access this property, doing little more than toggling the indicator on or off. In real-world use, you’ll likely perform your network activities on a secondary thread. Make sure you perform this property change on the main thread so the GUI can properly update itself. ptg 416 Chapter 10 Alerting Users Figure 10-11 The segmented control in Recipe 10-12 updates the applica- tion badge number. Recipe 10-11 Accessing the Status Bar’s Network Activity Indicator - (void) action: (id) sender { // Toggle the network activity indicator UIApplication *app = [UIApplication sharedApplication]; app.networkActivityIndicatorVisible = !app.networkActivityIndicatorVisible; } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. Recipe: Badging Applications If you’ve used the iPhone or iPod touch for any time, you’ve likely seen the small, red badges that appear over applications on the home screen.These might indicate the num- ber of missed phone calls or unread e-mails that have accumulated since the user last opened Phone or Mail. To set an application badge from within the program itself, set the applicationIcon ➥BadgeNumber property to an integer.To hide badges, set applicationIconBadgeNumber to 0 (the number zero). Recipe 10-12 demonstrates how to read and set an application badge. It matches the value of its segmented control to the most recently used badge number.When users change the segmented control setting, it updates the badge accord- ingly. Figure 10-11 shows this in action, displaying the interface within the application and the badge number it generates. Recipe 10-12 Reading and Updating Application Badges @implementation TestBedViewController - (void) updateBadge: (UISegmentedControl *) seg { // Set the badge number to the selected segment index [UIApplication sharedApplication].applicationIconBadgeNumber = seg.selectedSegmentIndex; ptg 417 Recipe: Simple Audio Alerts } - (void) viewDidLoad { // Create the segment control for selecting the badge number UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:[@"0 1 2 3 4 5" componentsSeparatedByString: @" "]]; seg.segmentedControlStyle = UISegmentedControlStyleBar; seg.selectedSegmentIndex = MIN([UIApplication sharedApplication].applicationIconBadgeNumber, 5); [seg addTarget:self action:@selector(updateBadge) forControlEvents:UIControlEventValueChanged]; self.navigationItem.titleView = seg; [seg release]; } @end Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. Recipe: Simple Audio Alerts Audio alerts “speak” directly to your users.They produce instant feedback—assuming users are not hearing impaired. Fortunately,Apple built basic sound playback into the Cocoa Touch SDK through System Audio services.This works very much like system audio on a Macintosh. The alternatives include using Audio Queue calls or AVAudioPlayer.Audio Queue playback is expensive to program and involves much more complexity than simple alert sounds need. In contrast, you can load and play system audio with just a few lines of code. AVAudioPlayer also has its drawbacks. It interferes with iPod audio. In contrast, System Audio can perform a sound without interrupting any music that’s currently playing, although that may admittedly not be the result you’re looking for, as alerts can get lost in the music. Alert sounds work best when kept short, preferably 30 seconds or shorter according to Apple. System Audio plays PCM and IMA audio only.That means limiting your sounds to AIFF,WAV, and CAF formats. System Sounds To build a system sound, call AudioServicesCreateSystemSoundID with a file URL pointing to the sound file.This call returns an initialized system sound object, which you can then play at will. Just call AudioServicesPlaySystemSound with the sound object. That single call does all the work. ptg 418 Chapter 10 Alerting Users AudioServicesPlaySystemSound(mySound); The default implementation of system sounds allows them to be controlled by the Sound Effects preference in Settings.When effects are disabled, the sound will not play.To over- ride this preference and always play the sound, you can set a property flag as such. // Identify it as a non UI Sound AudioServicesCreateSystemSoundID(baseURL, &mysound); AudioServicesPropertyID flag = 0; // 0 means always play AudioServicesSetProperty(kAudioServicesPropertyIsUISound, sizeof(SystemSoundID), &mysound, sizeof(AudioServicesPropertyID), &flag); When iPod audio is playing, the system sound generally plays back at the same volume, so users may miss your alert. Consider using vibration in addition to or in place of music.You can check the current playback state by testing as follows. Make sure you include <MediaPlayer/MediaPlayer.h> and link to the MediaPlayer framework. if ([MPMusicPlayerController iPodMusicPlayer].playbackState == MPMusicPlaybackStatePlaying) Add an optional system sound completion callback to notify your program when a sound finishes playing by calling AudioServicesAddSystemSoundCompletion. Unless you use short sounds that are chained one after another, this is a step you can generally skip. Clean up your sounds by calling AudioServicesDisposeSystemSoundID with the sound in question.This frees the sound object and all its associated resources. Note To use these system sound services, make sure to include AudioToolbox/AudioServices.h in your code and link to the Audio Toolbox framework. Vibration As with audio sounds, vibration immediately grabs a user’s attention.What’s more, vibra- tion works for nearly all users, including those who are hearing or visually impaired. Using the same System Audio services, you can vibrate as well as play a sound.All you need is the following one-line call to accomplish it, as used in Recipe 10-13: AudioServicesPlaySystemSound (kSystemSoundID_Vibrate); You cannot vary the vibration parameters. Each call produces a short one- to two-second buzz. On platforms without vibration support (like the iPod touch), this call does nothing—but will not produce an error. Alerts Audio Services provides a vibration/sound mashup called an alert sound, which is invoked as follows. AudioServicesPlayAlertSound(mySound); ptg 419 Recipe: Simple Audio Alerts This call, which is also demonstrated in Recipe 10-13, plays the requested sound and, pos- sibly, vibrates or plays a second alert. On iPhones, when the user has set Settings > Sound > Ring >Vibrate to ON, it vibrates the phone. Second generation and later iPod touch units play the sound sans vibration (which is unavailable on those units) through the onboard speaker. First generation iPod touches play a short alert melody in place of the sound on the device speaker while playing the requested audio through to the headphones. Delays The first time you play back a system sound on the iPhone, you may encounter delays. You may want to play a silent sound on application initialization to avoid a delay on sub- sequent playback. Note When testing on iPhones, make sure you have not enabled the silent ringer switch on the left side of the unit. This oversight has tripped up many iPhone developers. If your alert sounds must always play, consider using the AVAudioPlayer class, which is discussed in Chapter 15, “Audio, Video, and MediaKit.” Recipe 10-13 Playing Sounds, Alerts, and Vibrations Using Audio Services @implementation TestBedViewController - (void) playSound { if ([MPMusicPlayerController iPodMusicPlayer].playbackState == MPMusicPlaybackStatePlaying) AudioServicesPlayAlertSound(mysound); else AudioServicesPlaySystemSound(mysound); } - (void) vibrate { AudioServicesPlaySystemSound (kSystemSoundID_Vibrate); } - (void) viewDidLoad { // create the sound NSString *sndpath = [[NSBundle mainBundle] pathForResource:@"basicsound" ofType:@"wav"]; CFURLRef baseURL = (CFURLRef)[NSURL fileURLWithPath:sndpath]; // Identify it as not a UI Sound AudioServicesCreateSystemSoundID(baseURL, &mysound); AudioServicesPropertyID flag = 0; // 0 means always play AudioServicesSetProperty(kAudioServicesPropertyIsUISound, ptg 420 Chapter 10 Alerting Users sizeof(SystemSoundID), &mysound, sizeof(AudioServicesPropertyID), &flag); self.navigationItem.rightBarButtonItem = BARBUTTON(@"Sound", @selector(playSound)); self.navigationItem.leftBarButtonItem = BARBUTTON(@"Vibrate", @selector(vibrate)); } -(void) dealloc { // Clean up if (mysound) AudioServicesDisposeSystemSoundID(mysound); [super dealloc]; } @end Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. One More Thing: Showing the Volume Alert The iPhone offers a built-in alert that you can display to allow users to adjust the system volume. Figure 10-12 shows this alert, which consists of a slider and a Done button. Invoke this alert by issuing the following Media Player function. - (void) action { // Show the Media Player volume settings alert MPVolumeSettingsAlertShow(); } Test whether this alert is visible by issuing MPVolumeSettingsAlertIsVisible().This returns a Boolean value reflecting whether the alert is already onscreen. Hide the alert with MPVolumeSettingsAlertHide(), which dismisses the alert regardless of whether the user taps Done. For these functions to work, you must link to the MediaPlayer framework and import the media player headers. [...]... UITableViewController The standard iPhone table consists of a simple scrolling list of individual cells, providing a manipulatable data index Users may scroll or flick their way up and down until they find an item they want to interact with.Then, they can work with that item independently of other rows On the iPhone, tables are ubiquitous Nearly every standard software package uses them, and they form the core... long set of fonts.That’s because the list is based on the available fonts from the Macintosh running the SDK rather than the fonts on the iPhone itself Figure 11-1 It’s easy to fill a UITableView with cells based on any array of strings This table presents the font family list from the UIFont class When tapped, the chosen item updates the font on the navigation bar at the top Data Source Methods To display... This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 11 and open the project for this recipe Recipe: Changing a Table’s Background Color To use a color for your table’s background other than white, use the table view’s backgroundColor... Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 11 and open the project for this recipe Updating the Background Color to Reflect the Degree of Scrolling Because UITableViews are a subclass of the UIScrollView class, you can... Laying Out the View UITableViews instances are, as the name suggests, views.They present interactive tables on the iPhone screen .The UITableView class inherits from the UIScrollView class.This inheritance provides the up and down scrolling capabilities used by the table Like other views, UITableView instances define their boundaries through frames, and they can be children or parents of other views.To... } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 11 and open the project for this recipe Recipe: Exploring Cell Types The iPhone offers four kinds of base table view cells.These types, which are shown in Figure 11-3, provide... traits.You can change the image it shows, the color of its font, and the cell’s background.These are set via the selectedImage, selectedTextColor, and selectedBackgroundView properties The selected image replaces any image you have added to a cell (via the image property, as shown in Recipe 11-4) when the user selects the cell .The selected version should use the same size as the original so the cell layout... cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [av show]; } @end Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 11 and open the project for this recipe Recipe: Remembering Control State for Custom Cells Cells... numberWithBool:aSwitch.on] forKey: anItem]; } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 11 and open the project for this recipe Visualizing Cell Reuse Recipe 11-8 helps fix problems with cell/model discrepancies .The following... lastObject]; // Set the cell text [(UILabel *)[cell viewWithTag:101] setText: [[UIFont familyNames] objectAtIndex:indexPath.row]]; return cell; } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 11 and open the project for this recipe . http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. Recipe:. get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for. http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 10 and open the project for this recipe. Recipe:

Ngày đăng: 13/08/2014, 18:20

TỪ KHÓA LIÊN QUAN