1 前言
UIDatePicker是一个十分类似于UIPickerView的类,十分常用,今天我们来学习一下。
2 UIDatePicker简介
上代码
日期选择:
.h文件:
@property(nonatomic,strong) UIDatePicker *myDatePicker;
.m文件:
@synthesize myDatePicker;
- (void)viewDidLoad
{
//一年的秒数
float oneYearTime = 60*60*24*365;
NSLog(@"oneYearTime====>%f",oneYearTime);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
//事件选择器
self.myDatePicker = [[UIDatePicker alloc] init];
self.myDatePicker.center = self.view.center;
self.myDatePicker.datePickerMode=UIDatePickerModeDate;
//添加事件
[self.myDatePicker addTarget:self action:@selector(datePickerDateChanged:) forControlEvents:UIControlEventValueChanged];
//获得当前时间
NSDate *currentDate = self.myDatePicker.date;
NSLog(@"Date = %@",currentDate);
NSDate *oneYearFromToday = [currentDate dateByAddingTimeInterval:oneYearTime];
NSDate *twoYearFromToday = [currentDate dateByAddingTimeInterval:2*oneYearTime];
//最小可选时间
self.myDatePicker.minimumDate = oneYearFromToday;
self.myDatePicker.maximumDate = twoYearFromToday;
[self.view addSubview:self.myDatePicker];
}
-(void) datePickerDateChanged:(UIDatePicker *)paramDatePicker{
if ([paramDatePicker isEqual:self.myDatePicker]) {
NSLog(@"Selected date=%@",paramDatePicker);
}
}
运行效果:
.m文件:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.view.backgroundColor = [UIColor whiteColor];
//事件选择器
self.myDatePicker = [[UIDatePicker alloc] init];
self.myDatePicker.center = self.view.center;
//设置成时间模式
self.myDatePicker.datePickerMode=UIDatePickerModeCountDownTimer;
[self.view addSubview:self.myDatePicker];
NSTimeInterval twoMinutes = 2*60;
[self.myDatePicker setCountDownDuration:twoMinutes];
}
UIDatePickerMode类型:
-type enmu{
UIDatePickerModeTime,//时间
UIDatePickerModeDate,//日期
UIDatePickerModeDateAndTime,//时间和日期
UIDatePickerModeCountDownTimer//倒计时模式
}
运行结果:
3 结语
以上就是UIDatePicker的一些简单介绍,希望能帮到大家。