UIDatePicker是一个可以用来选择或者设置日期的控件,不过它是像转轮一样的控件,而且是苹果专门为日历做好的控件,如下图所示:
除了UIDatePicker控件,还有一种更通用的转轮形的控件:UIPickerView,只不过UIDatePicker控件显示的就是日历,而UIPickerView控件中显示的内容需要我们自己用代码设置。本篇文章简单介绍UIDatePicker控件,后边的文章会介绍UIPickerView。
1、运行Xcode 4.2,新建一个Single View Application,名称为UIDatePicker Test,其他设置如下图所示:
2、单击ViewController.xib,打开Interface Builder。拖一个UIDatePicker控件到视图上:
3、然后拖一个按钮在视图上,并修改按钮名称为Select:
单击按钮后,弹出一个Alert,用于显示用户所作选择。
4、创建映射:打开Assistant Editor,选中UIDatePicker控件,按住Control,拖到ViewController.h中:
新建一个Outlet,名称为datePicker:
然后以同样的方式为按钮建立一个Action映射,名称为buttonPressed,事件类型为默认的Touch Up Inside。
5、选中UIDatePicker控件,打开Attribute Inspector,在其中设置Maximum Date为2100-12-31:
6、单击ViewController.m,找到buttonPressed方法,在其中添加代码如下:
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]; |
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" |
13 | cancelButtonTitle:@ "Yes, I did." |
14 | otherButtonTitles:nil]; |
其中NSDate *selected = [datePicker date];用于获得UIDatePicker所选择的日期和时间,后边的三行代码把日期和时间改成东八区的时间格式。
找到viewDidLoad方法,添加代码如下:
5 | NSDate *now = [NSDate date]; |
6 | [datePicker setDate:now animated:NO]; |
找到viewDidUnload方法,添加代码:
3 | [self setDatePicker:nil]; |
7、现在运行,显示如下图所示: