很多时候我们会用到时间选择器,UIDatePicker,很显然,系统提供的日期选择器很多时候不能满足我们的需求。
通常UIDatePicker作为一个和view类似的子控件弹出,但是作为控件加到父控件中之后,可能父控件的frame不是我们想要的结果
这里将时间选择器封装在一个控制器里面,用模态的方式弹出,就始终可以在最底下弹出了。效果如下
使用参见ViewController.m
//点击弹出时间选择器控制器
- (IBAction)clickDatePicker:(id)sender {
HooDatePickerViewController *dateViewController = [[self storyboard] instantiateViewControllerWithIdentifier:NSStringFromClass([HooDatePickerViewController class])];
dateViewController.delegate = self;
//更换pickerMode则可弹出不同类型的时间控制器
dateViewController.pickerMode = HooDatePickerModeYear;
//注意这个modalPresentationStyle一定要设置,要不然模态出来的控制器背景是黑的
dateViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:dateViewController animated:YES completion:nil];
}
实现代理
#pragma mark - HooDatePickerViewControllerDelegete
- (void)topViewClicked {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)cancelButtonClicked {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sureButtonClickedWithDate:(NSDate *)date {
self.selectedDate = date;
[self dismissViewControllerAnimated:YES completion:nil];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
NSString *dateString = [formatter stringFromDate:self.selectedDate];
NSLog(@"dateString = %@",dateString);
}