UIDatePicker提供了一个快速选择日期和时间的控件,他是UIControl的子类,专门用于日期时间的选择。其样式能够经过UIDatePicker的属性进行灵活设置,同时也能够获取到当前UIDatePicker的值。UIDatePicker有几个方法和属性须要重点掌握。ide
@property (nonatomic) UIDatePickerMode datePickerMode; //设置UIDatePicker的展现样式,有四种样式atom
UIDatePickerModeTime, // 仅显示时间
UIDatePickerModeDate, // 显示年月日
UIDatePickerModeDateAndTime, // 显示年月日和时间
UIDatePickerModeCountDownTimer //倒计时spa
@property (nullable, nonatomic, strong) NSLocale *locale; //设置地区,地区的设置会影响日期以及时间文字的展现方式
@property (nullable, nonatomic, strong) NSTimeZone *timeZone; //设置时区code
@property (nonatomic, strong) NSDate *date; //获取当前日期/时间值orm
- (void)setDate:(NSDate *)date animated:(BOOL)animated;//设置当前显示的日期时间blog
下面来看一个完整示例,选择时间后点击肯定按钮会弹出提示框,提示框内容为选择的时间字符串
#import "ViewController.h" @interface ViewController () @property(nonatomic,strong)UIDatePicker *datePicker; @property(nonatomic,strong)UIButton *button; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view addSubview:self.datePicker]; [self.view addSubview:self.button]; } //懒加载 - (UIDatePicker *)datePicker{ if (_datePicker == nil) { self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 280, self.view.frame.size.width, 200)]; _datePicker.datePickerMode = UIDatePickerModeDateAndTime; _datePicker.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]; } return _datePicker; } //懒加载按钮,用于展现datePicker选中的时间 - (UIButton *)button{ if (_button == nil) { self.button = [[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 50) / 2.0, 100, 50, 30)]; [_button setTitle:@"肯定" forState:UIControlStateNormal]; _button.backgroundColor = [UIColor blueColor]; [_button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside]; } return _button; } //肯定按钮被点击 - (void)clickButton{ //获取用户经过UIDatePicker设置的时间 NSDate *date = [self.datePicker date]; //建立一个日期格式器 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; //为日期格式器设置格式字符串 [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm +0800"]; //使用日期格式器格式化日期和时间 NSString *dateString = [dateFormatter stringFromDate:date]; NSString *message = [NSString stringWithFormat:@"您选择的日期和时间是:%@",dateString]; //警告框 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"日期和时间" message:message preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *action = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:nil]; [alert addAction:action]; [self presentViewController:alert animated:YES completion:nil]; } @end
运行截图:get