iOS开发10:UIDatePicker控件

UIDatePicker是一个能够用来选择或者设置日期的控件,不过它是像转轮同样的控件,并且是苹果专门为日历作好的控件,以下图所示:ide

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

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

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

三、而后拖一个按钮在视图上,并修改按钮名称为Select:事件

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

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

新建一个Outlet,名称为datePicker:io

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

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

六、单击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;
}

七、如今运行,显示以下图所示:

 

相关文章
相关标签/搜索