iOS开发 加入小组

412个成员 1424个话题 创建时间:2012-03-15

iOS开发10:UIDatePicker控件

发表于 2012-09-04 14233 次查看

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方法,在其中添加代码如下:

- (IBAction)buttonPressed:(id)sender {
    NSDate *selected = [datePicker date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm +0800"];
    NSString *destDateString = [dateFormatter stringFromDate:selected];
    
    NSString *message = [[NSString alloc] initWithFormat: 
                         @"The date and time you selected is: %@", destDateString]; 
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle:@"Date and Time Selected" 
                          message:message
                          delegate:nil 
                          cancelButtonTitle:@"Yes, I did." 
                          otherButtonTitles:nil]; 
    [alert show]; 
}

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

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

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    NSDate *now = [NSDate date];
    [datePicker setDate:now animated:NO]; 
}

找到viewDidUnload方法,添加代码:

- (void)viewDidUnload
{
    [self setDatePicker:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.datePicker = nil;
}

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

 

发表回复
功能维护升级中,维护完成完后将再次开放,非常抱歉给您学习造成的不便。