iOS基础 -- UIDatePicker

/**
     *  UIDatePicker
     */
    
    self.myDatePicker = [[UIDatePicker alloc] init];
    self.myDatePicker.center = self.view.center;
    [self.myDatePicker addTarget:self action:@selector(datePickerDateChanged:) forControlEvents:UIControlEventValueChanged];
    //[self.view addSubview:self.myDatePicker];

如上,添加UIDatePicker到当前view,target方法如下:

-(void) datePickerDateChanged: (UIDatePicker *)paramDatePicker
{
    if([paramDatePicker isEqual:self.myDatePicker]){
        NSLog(@"%@",paramDatePicker.date);
    }
}

这就是一个最简单地UIDatePicker的使用,他显示了当前的日期、时间、AM/PM。然后在datePickerDateChanged中捕获变化,然后通过date方法,获取当前选定的日期和时间。

UIDatePicker可以通过datePickerMode属性来设置不同的显示方法,具体属性如下所示:

typedef NS_ENUM(NSInteger, UIDatePickerMode) {
    UIDatePickerModeTime,           // Displays hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. 6 | 53 | PM)
    UIDatePickerModeDate,           // Displays month, day, and year depending on the locale setting (e.g. November | 15 | 2007)
    UIDatePickerModeDateAndTime,    // Displays date, hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. Wed Nov 15 | 6 | 53 | PM)
    UIDatePickerModeCountDownTimer, // Displays hour and minute (e.g. 1 | 53)
};

它的默认参数为UIDatePickerModeDateAndTime,此外可以通过minimumDate和maximumDate来进行可选范围的规定。如下例所示:

    self.myDatePicker.datePickerMode = UIDatePickerModeDate;
    NSTimeInterval oneYearTime = 365*24*60*60;
    NSDate *today = [NSDate date];
    NSDate *oneYearFromDay = [today dateByAddingTimeInterval:oneYearTime];
    NSDate *twoYearFromDay = [today dateByAddingTimeInterval:oneYearTime * 2];
    self.myDatePicker.minimumDate = oneYearFromDay;
    self.myDatePicker.maximumDate = twoYearFromDay;
下面是CountDown模式的一个实例:

self.myDatePicker.datePickerMode = UIDatePickerModeCountDownTimer;
    NSTimeInterval towMinutes = 2*60;
    [self.myDatePicker setCountDownDuration:towMinutes];



你可能感兴趣的:(iOS)