传统方式
一般情况下弹出日期选择的场景是:用户点击UITextField弹出日期选择,关键代码如下:
点击UITextField弹出日期选择
1
2
3
|
UITextField *textField; textField.inputView = [[UIDatePicker alloc] init]; textField.inputAccessoryView = [[UIToolbar alloc] init]; |
但是inputView,inputAccessoryView是在UIView的父类UIResponder中定义的只读属性,UITextField重写了这2个属性并且将readonly修改成readwrite
UIResponder
1
2
|
@property (nullable, nonatomic, readonly, strong) UIView *inputView; @property (nullable, nonatomic, readonly, strong) UIView *inputAccessoryView; |
UITextField
1
2
|
@property (nullable, readwrite, strong) UIView *inputView; @property (nullable, readwrite, strong) UIView *inputAccessoryView; |
这就意味着对于普通的UIView我们是不能通过设置inputView,inputAccessoryView来弹出日期选择的。
UIViewControler模态弹出方式
这里我们使用ViewController模态弹出的方式实现,它可以在任何时候你想选择日期时都可以弹出来,而不局限于通过inputView,inputAccessoryView属性。
调用方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
- ( void ) showDatePicker
{ ISSDatePickerViewController * viewController = [[ISSDatePickerViewController alloc] init];
viewController.minDate = [NSDate dateFromString 3 : @ "1900-1-1" ];
viewController.maxDate = [NSDate new ];
viewController.delegate = self;
viewController.datePickerMode = UIDatePickerModeDate;
viewController.currentDate = [NSDate new ];
if ( IS_IOS 8 _OR_LATER )
{
viewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}
else
{
viewController.modalPresentationStyle = UIModalPresentationCurrentContext;
}
[self presentViewController : viewController animated : YES completion : ^ {
viewController. view .backgroundColor = RGBAColor ( 0 , 0 , 0 , 0.3 ) ;
} ];
} #pragma mark ISSDatePickerViewControllerDelegate - ( void ) onDatePicked : ( NSDate * ) date
{ } |
效果图: