设置UIDatePicker的时间显示范围

设置UIDatePicker显示时间段

1.定义两个实力变量

UIDatePicker*datePicker; //日期属性

UIToolbar*inputAccessoryView;//日期上方的取消和确定视图

2.初始化控件

- (void)setDatePickerStyle {

if(!inputAccessoryView)

{

inputAccessoryView= [[UIToolbaralloc]init];

inputAccessoryView.barStyle=UIBarStyleDefault;

inputAccessoryView.autoresizingMask=UIViewAutoresizingFlexibleHeight;

[inputAccessoryViewsizeToFit];

inputAccessoryView.frame=CGRectMake(0,kScreenHeight,kScreenWidth,44);

UIBarButtonItem*cancelBtn = [[UIBarButtonItemalloc]initWithTitle:@"取消"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(cancel:)];

UIBarButtonItem*doneBtn = [[UIBarButtonItemalloc]initWithTitle:@"确定"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(done:)];

UIBarButtonItem*flexibleSpaceLeft = [[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpacetarget:nilaction:nil];

NSArray*array = [NSArrayarrayWithObjects:cancelBtn,flexibleSpaceLeft, doneBtn,nil];

[inputAccessoryViewsetItems:array];

[[[UIApplicationsharedApplication].delegatewindow]addSubview:inputAccessoryView];

}

if(!datePicker) {

datePicker= [[UIDatePickeralloc]init];

datePicker.frame=CGRectMake(0,kScreenHeight,kScreenWidth,216);

datePicker.backgroundColor= [UIColorlightGrayColor];

//设置区域为中国简体中文

datePicker.locale= [[NSLocalealloc]initWithLocaleIdentifier:@"zh_CN"];

//设置picker的显示模式:只显示日期

datePicker.datePickerMode=UIDatePickerModeDate;

//设置时间可选择的范围:前七天--(七天时间)--今天

datePicker.minimumDate= [NSDatedateWithTimeInterval:-6*24*60*60sinceDate:[NSDatedate]];//七天前的那天

datePicker.maximumDate= [NSDatedate];//今天

[datePickeraddTarget:selfaction:@selector(dateChanged:)forControlEvents:UIControlEventValueChanged];

[[[UIApplicationsharedApplication].delegatewindow]addSubview:datePicker];//添加到主窗口上,也可以添加到当前视图上(根据需求而定)

}

}

3.点击按钮, 触发datepickerShow()方法,选择时间

- (void)datepickerShow

{

[UIViewanimateWithDuration:.3animations:^{

datePicker.frame=CGRectMake(0,kScreenHeight-216,kScreenWidth,216);

inputAccessoryView.frame=CGRectMake(0,kScreenHeight-216-44,kScreenWidth,44);

}completion:^(BOOLfinished) {

}];

}

4.inputAccessoryView的取消和确定操作

//取消

- (void)cancel:(UIBarButtonItem*)sender {

[UIViewanimateWithDuration:.3animations:^{

datePicker.frame=CGRectMake(0,kScreenHeight,kScreenWidth,216);

inputAccessoryView.frame=CGRectMake(0,kScreenHeight,kScreenWidth,44);

}completion:^(BOOLfinished) {

}];

}

//确定

- (void)done:(UIBarButtonItem*)sender {

[UIViewanimateWithDuration:.3animations:^{

datePicker.frame=CGRectMake(0,kScreenHeight,kScreenWidth,216);

inputAccessoryView.frame=CGRectMake(0,kScreenHeight,kScreenWidth,44);

}completion:^(BOOLfinished) {

    //需要进行的操作

}];

}


5.UIDatePicker--- delegate 

- (void)dateChanged:(UIDatePicker*)sender {

//将日期转换成需要的样式

NSDateFormatter* YMD = [[NSDateFormatteralloc]init];

[YMDsetDateFormat:@"yyyy-MM-dd"];


}

你可能感兴趣的:(设置UIDatePicker的时间显示范围)