UIDatePicker控件

UIDatePicker是一个可以用来选择或者设置日期的控件,不过它是像转轮一样的控件,而且是苹果专门为日历做好的控件,如下图所示:

除了UIDatePicker控件,还有一种更通用的转轮形的控件:UIPickerView,只不过UIDatePicker控件显示的就是日历,而UIPickerView控件中显示的内容需要我们自己用代码设置。本篇文章简单介绍UIDatePicker控件,后边的文章会介绍UIPickerView。

1、运行Xcode 4.2,新建一个Single View Application,名称为UIDatePicker Test,其他设置如下图所示:

UIDatePicker控件_第1张图片

2、单击ViewController.xib,打开Interface Builder。拖一个UIDatePicker控件到视图上:

UIDatePicker控件_第2张图片

3、然后拖一个按钮在视图上,并修改按钮名称为Select:

单击按钮后,弹出一个Alert,用于显示用户所作选择。

4、创建映射:打开Assistant Editor,选中UIDatePicker控件,按住Control,拖到ViewController.h中:

新建一个Outlet,名称为datePicker:

UIDatePicker控件_第3张图片

然后以同样的方式为按钮建立一个Action映射,名称为buttonPressed,事件类型为默认的Touch Up Inside。

5、选中UIDatePicker控件,打开Attribute Inspector,在其中设置Maximum Date为2100-12-31:

UIDatePicker控件_第4张图片

6、单击ViewController.m,找到buttonPressed方法,在其中添加代码如下:

view source
print ?
01 - (IBAction)buttonPressed:(id)sender {
02     NSDate *selected = [datePicker date];
03     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
04     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm +0800"];
05     NSString *destDateString = [dateFormatter stringFromDate:selected];
06       
07     NSString *message = [[NSString alloc] initWithFormat: 
08                          @"The date and time you selected is: %@", destDateString]; 
09     UIAlertView *alert = [[UIAlertView alloc] 
10                           initWithTitle:@"Date and Time Selected" 
11                           message:message
12                           delegate:nil 
13                           cancelButtonTitle:@"Yes, I did." 
14                           otherButtonTitles:nil]; 
15     [alert show]; 
16 }

其中NSDate *selected = [datePicker date];用于获得UIDatePicker所选择的日期和时间,后边的三行代码把日期和时间改成东八区的时间格式。

找到viewDidLoad方法,添加代码如下:

view source
print ?
1 - (void)viewDidLoad
2 {
3     [super viewDidLoad];
4     // Do any additional setup after loading the view, typically from a nib.
5     NSDate *now = [NSDate date];
6     [datePicker setDate:now animated:NO]; 
7 }

找到viewDidUnload方法,添加代码:

view source
print ?
1 - (void)viewDidUnload
2 {
3     [self setDatePicker:nil];
4     [super viewDidUnload];
5     // Release any retained subviews of the main view.
6     // e.g. self.myOutlet = nil;
7     self.datePicker = nil;
8 }

7、现在运行,显示如下图所示:

  UIDatePicker控件_第5张图片

你可能感兴趣的:(Date,xcode,application,action,日历,interface)