what do the UIPickerView and the UIImagePicker classes have in common? Nothing, really, other than they are both ultimately UIViews. But they are both controls you might use in an iPhone application, and so they are covered together in this second chapter on iPhone controls. This chapter’s first half covers using the UIDatePicker and UIPickerView classes. These classes create visual controls that appear similar to Las Vegas slot machines. This chapter’s second half covers using the UIImagePickerController. This class allows programmatically accessing an iPhone’s camera, camera roll, and photo library.
You use pickers to select one of several values. There are two types of pickers: Date Pickers and Pickers. Date pickers are used for selecting a date, time, or countdown interval. Pickers are used for selecting one of many values.
Date pickers pick dates and times, placing the selected values in an NSDate class, and are implemented using the UIDatePicker class. If using Interface Builder to develop an iPhone application, you drag a date picker onto your view’s canvas from the library and modify the picker’s properties in the Inspector. You then create an IBOutlet for the picker in your view’s associated view controller and connect it to the picker on your view’s canvas. The view controller uses this outlet to obtain the UIDatePicker object’s selected date. The example later in this section illustrates this process.
A UIDatePicker has rotating wheels, allowing a user to select the date and time. If using a date picker to pick a date and time, valid modes are Date & Time, Time, and Date. If using a date picker to pick a countdown time, the valid mode is Timer. Figure 13-1 illustrates the picker’s visual appearance for the different modes.
Figure 13-1 UIDatePicker has four modes: Date & Time, Time, Date, and Timer.
There are several attributes you might change from the default when using a UIDatePicker. Figure 13- 2 illustrates the mode, locale, timeZone, date, minimumDate, maximumDate, and interval properties, as viewed in the Inspector. The locale is an NSLocale. This class encapsulates how the date should be formatted for a different date or culture. The timeZone is an NSTimeZone; its default value is the operating system’s time zone. The minuteInterval is the minute intervals displayed by the picker. For instance, Figure 13- 3 illustrates a UIDatePicker using 30-minute intervals and a UIDatePicker using 1-minute intervals.
UIDatePickers return values as an NSDate. You access a date picker’s value through its date property. For instance, the following sets an NSDate from a UIDatePicker’s date property. NSDate * theDate = self.datePicker.date; An NSDate is a date and time. Several NSDate methods you might use include isEqualToDate:, earlierDate:, compare:, and laterDate:. For a more complete understanding of date and time programming, refer to Apple’s ―Date and Time Programming Guide for Cocoa,‖ available online.
Figure 13-2 Several UIDatePicker properties you might change in the Inspector
Figure 13-3 A UIDatePicker showing 30-minute intervals and a UIDatePicker showing 1-minute intervals
When you wish to display a date, you use an NSDateFormatter. An NSDateFormatter allows a date to be displayed as a formatted NSString. There are many formats you might use. For instance, consider the two formatters. NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"MM/dd/yyyy"]; The ―MM/dd/yyyy‖ format outputs August 26, 2008, as ―08/26/2008." [dateFormatter setDateFormat:@"EEEE MMMM d',' yyyy"]; The ―EEEE MMMM d’,’ yyyy‖ format outputs ―Tuesday August 26, 2008,‖ as the date. These are only two of many choices you might select to format dates and times. For more formats, refer to Apple’s ―Data Formatting Programming Guide for Cocoa,‖ available online.
Figure 13-4 Adding a UIDatePicker and UILabel to the view
Figure 13-5 Change a UIDatePicker’s mode to Date
Figure 13-6 Connecting to the UIDatePicker’s value changed event
Figure 13-7 The application running in iPhone Simulator
Listing 13-1 DatePickerProjectViewController.h #import <UIKit/UIKit.h> @interface DatePickerProjectViewController : UIViewController { IBOutlet UIDatePicker * datePicker; IBOutlet UILabel * theLabel; } @property (nonatomic, retain) IBOutlet UIDatePicker * datePicker; @property (nonatomic, retain) IBOutlet UILabel * theLabel; - (IBAction) changeValue: (id) sender; @end Listing 13-2 DatePickerProjectViewController.m #import "DatePickerProjectViewController.h" @implementation DatePickerProjectViewController @synthesize datePicker; @synthesize theLabel; - (IBAction) changeValue: (id) sender { NSDate * theDate = self.datePicker.date; NSLog(@"the date picked is: %@", [theDate description]); NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"MM/dd/yyyy"]; NSLog(@"formatted: %@", [dateFormatter stringFromDate:theDate]); [dateFormatter setDateFormat:@"EEEE MMMM d',' yyyy"]; NSLog(@"formatted: %@", [dateFormatter stringFromDate:theDate]); [theLabel setText:[theDate description]]; } - (void)dealloc { [datePicker release]; [theLabel release]; [super dealloc]; } @end Listing 13-3 Debugger console output 2009-02-02 19:38:03.794 DatePickerProject[1033:20b] the date picked is: 2008-11-26 21:00:00 -0500 2009-02-02 19:38:03.795 DatePickerProject[1033:20b] formatted: 11/26/2008 2009-02-02 19:38:03.796 DatePickerProject[1033:20b] formatted: Wednesday November 26, 2008
UIDatePicker classes are also useful for selecting a duration for an NSTimer. A UIDatePicker selects an NSDate, which consists of a date and a time; therefore, you can create a timer using an NSDate’s time. But a UIDatePicker does not implement a timer; it only provides a visual way to pick duration. You must then use this duration with an NSTimer. This task illustrates using a UIDatePicker to select a duration for an NSTimer and, in the process, illustrates using the NSCalendar, NSDateFormatter, and NSDateComponents classes.
Figure 13-8 Adding a button to the canvas Figure 13-9 Running the application in iPhone Simulator
Listing 13-4 ATimerViewController.h #import <UIKit/UIKit.h> @interface ATimerViewController : UIViewController { IBOutlet UIDatePicker * timePicker; } @property (nonatomic, retain) IBOutlet UIDatePicker * timePicker;
@end Listing 13-5 ATimerViewController.m #import "ATimerViewController.h" @implementation ATimerViewController @synthesize timePicker; NSInteger seconds = 0; - (IBAction) echoTime: (id) sender { NSDate * time = timePicker.date; NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"HH:MM:SS"]; NSLog(@"date: %@",[dateFormatter stringFromDate:time]); NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; NSDateComponents * comps = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:time]; NSInteger hour = [comps hour]; NSInteger minute = [comps minute]; NSLog(@"Hour: %i", hour); NSLog(@"minute: %i", minute); NSInteger secs = hour * 60 * 60 + minute * 60; NSNumber * elapsedSeconds = [[NSNumber alloc] initWithInt:secs]; NSDictionary * myDict = [NSDictionary dictionaryWithObject: elapsedSeconds forKey:@"TotalSeconds"]; [NSTimer scheduledTimerWithTimeInterval:1 target: self selector: @selector(echoIt:) userInfo: myDict repeats: YES]; } - (void) echoIt: (NSTimer *) timer { NSNumber * num = (NSNumber *) [[timer userInfo] valueForKey:@"Total Seconds"]; seconds++; NSInteger secs = [num integerValue] - seconds; NSLog(@"elapsed: %i, remaining: %i", seconds, secs); }(void)dealloc { [timePicker release]; [super dealloc]; } @end Listing 13-6 The ATimer application logging to debugger console 2009-02-06 07:35:21.813 ATimer[540:20b] date: 01:12:00 2009-02-06 07:35:21.814 ATimer[540:20b] Hour: 1 2009-02-06 07:35:21.814 ATimer[540:20b] minute: 11 2009-02-06 07:35:22.815 ATimer[540:20b] elapsed: 1, remaining: 4259 2009-02-06 07:35:23.815 ATimer[540:20b] elapsed: 2, remaining: 4258 --- snip --- 2009-02-06 07:35:31.815 ATimer[540:20b] elapsed: 10, remaining: 4250 This example code involves several concepts not covered elsewhere in this book. Notice the NSDictionary, NSCalendar, and NSDateComponents classes. The UIDatePicker picks the hours and minutes for the timer. Upon clicking the button, the echoTime method creates an NSCalendar and obtains date components from the time. After obtaining the total seconds, echoTime adds the seconds to an NSDictionary and creates a timer that fires every second. When firing, the timer calls the echoIt method, passing itself and the dictionary as parameters. The echoIt method obtains the seconds from the userInfo parameter. The echoIt method then determines the elapsed seconds and logs it to the Debugger Console.
You liked the article?
Like: 0
Vote for difficulty
Current difficulty (Avg): Medium
TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.