免费开源的iOS开发学习平台

UIDatePicker详解:2-UIDatePicker基本使用

本节我们通过示例演示一下UIDatePicker的基本使用方法。

  • 在控制器类中,添加UIDatePicker类型的属性
@interface ViewController ()
@property(nonatomic, strong) UIDatePicker *datePicker;
@property(nonatomic, strong) UIButton *button;
@end
  • 使用懒加载的方式,设置UIDatePicker对象的属性,使其支持中文并且可以显示日期与时间。
- (UIDatePicker *)datePicker{
    if (_datePicker == nil) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 220, [UIScreen mainScreen].bounds.size.width, 300)];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        _datePicker.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    }
    return _datePicker;
}
  • 初始化按钮,用于展示UIDatePicker的选中时间。
- (UIButton *)button{
    if (_button == nil) {
        _button = [UIButton buttonWithType:UIButtonTypeSystem];
        _button.frame = CGRectMake(0, 0, 50, 30);
        _button.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, 600);
        [_button setTitle:@"确定" forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}
  • 在viewDidLoad方法中添加子控件。
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.datePicker];
    [self.view addSubview:self.button];
}
  • 实现按钮的点击方法,当点击按钮时会弹出一个提示框,显示当前选中的日期。
- (void)clickButton {
    //获取用户通过UIDatePicker设置的日期和时间
    NSDate *selected = [self.datePicker date];
    //创建一个日期格式器
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //为日期格式器设置格式字符串
    [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm +0800"];
    //使用日期格式器格式化日期和时间
    NSString *destDateString = [dateFormatter stringFromDate:selected];
    NSString *message = [NSString stringWithFormat:@"您选择的日期和时间是: %@",destDateString];
    //警告框
    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];
}

运行效果:

示例代码

https://github.com/99ios/10.6.2