6

在我的项目中,我需要显示日期选择器 18,并且我需要锁定 80 年,所以我如何在 datepicker 中显示这些日期,任何人都可以帮助我在这里找到我添加代码我在日志中打印的代码,但我需要在我的日期选择器上显示,所以我该如何显示

NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDate * currentDate = [NSDate date];
NSDateComponents * comps = [[NSDateComponents alloc] init];
[comps setYear: -18];
NSDate * minDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: 0];
[comps setYear: -100];
NSDate * maxDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: 0];
[comps release];

self.datePickerView.minimumDate = minDate;
self.datePickerView.maximumDate = maxDate;

NSLog(@"minDate   %@", minDate);
NSLog(@"maxDate%@", maxDate);
4

2 回答 2

21

嗨,首先,最短日期必须是 100 年前的日期,最长日期必须是 18 年前的日期,然后将 pickerView 的日期设置为日期范围之间的日期,这样您的最终代码将如下所示

NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDate * currentDate = [NSDate date];
NSDateComponents * comps = [[NSDateComponents alloc] init];
[comps setYear: -18];
NSDate * maxDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: 0];
[comps setYear: -100];
NSDate * minDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: 0];
[comps release];

self.datePickerView.minimumDate = minDate;
self.datePickerView.maximumDate = maxDate;
self.datePickerView.date = minDate;

希望这对您有所帮助。

于 2012-10-12T07:29:06.127 回答
2

这是视图控制器类的 viewDidLoad 方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
    NSDate * currentDate = [NSDate date];
    NSDateComponents * comps = [[NSDateComponents alloc] init];
    [comps setYear: -18];
    NSDate * maxDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: 0];
    [comps setYear: -100];
    NSDate * minDate = [gregorian dateByAddingComponents: comps toDate: currentDate options: 0];
    [comps release];



    UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
    [pickerView setMinimumDate:minDate];
    [pickerView setMaximumDate:maxDate];
    [pickerView setDate:minDate];
    [[self view] addSubview:pickerView];

}

我的输出是

在此处输入图像描述

你能把你的输出分享为截图吗?

于 2012-10-12T10:20:08.060 回答