2013-05-07 78 views
1

我在試圖限制日期時遇到了問題。通過設置這樣的日期self.datePicker.maximumDate = [NSDate date];它現在只是灰色的日期,但使用戶能夠在此最大日期之後選擇一個日期。iOS UIDatePicker set max date

所以當選擇器值發生變化時,我比較所選日期,如果超過了當前日期,我編輯它。

如果我使用這兩種解決方案我得到了奇怪的行爲,任何想法?當從日期選擇器的日期值做變化

- (IBAction)pickerValueChanged:(id)sender { 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     UIDatePicker *datePicker = (UIDatePicker *)sender; 

     if ([self.datePicker.date compare:[NSDate date]] == NSOrderedDescending) { 

      datePicker.date = [NSDate date]; 
     } 

    }); 
} 

此功能被觸發。如果我設置了最低和最高日期,我會有一個奇怪的行爲。 有什麼想法?

編輯:

+0

你在哪裏設置self.datePicker.maximumDate = [NSDate date]; – 2013-05-07 06:43:10

+0

在ViewController中的viewDidLoad方法 – 2013-05-07 07:01:26

回答

2

是的,你可以設置最小和最大日期,使用的.xib和選擇器設置

enter image description here

-1
- (IBAction) datePickerChanged:(id)sender { 
// When `setDate:` is called, if the passed date argument exactly matches the Picker's date property's value, the Picker will do nothing. So, offset the passed date argument by one second, ensuring the Picker scrolls every time. 
NSDate* oneSecondAfterPickersDate = [picker.date dateByAddingTimeInterval:1] ; 
if ([picker.date compare:picker.minimumDate] == NSOrderedSame) { 
    NSLog(@"date is at or below the minimum") ; 
    picker.date = oneSecondAfterPickersDate ; 
} 
else if ([picker.date compare:picker.maximumDate] == NSOrderedSame) { 
    NSLog(@"date is at or above the maximum") ; 
    picker.date = oneSecondAfterPickersDate ; 
    } 
} 
+0

我討厭那些沒有提供它做什麼的描述的答案,所以我給了-1這個答案應該包括描述的原因是因爲如果一個新手在尋找答案,他們可能不會理解什麼是一個只有代碼的文章實際上是什麼 – Popeye 2016-01-05 09:14:57

-1
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDate *currentDate = [NSDate date]; 
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:currentDate]; 
NSInteger year = [components year]; 

NSDateFormatter* formatter1 = [[NSDateFormatter alloc] init]; 
[formatter1 setDateFormat:@"yyyy-MM-dd"]; 
NSString *dateString = [NSString stringWithFormat:@"%ld-12-31",(long)year]; 
NSDate *maxDate = [formatter1 dateFromString:dateString]; 
[self.dobPickerView setMaximumDate: maxDate]; 
+0

我討厭那些沒有提供它所做的事情的描述,所以我給這個-1。爲什麼答案應該包括描述的原因是因爲如果新手正在尋找一個答案,他們可能不明白什麼是一個只有代碼的職位實際上。 – Popeye 2016-01-05 09:14:34

3

要麼你可以設置最大日在Xcode或編程。

1.通過使用下面的代碼行,您可以設置選擇器的最大日期。

[self.yourPickerView setMaximumDate: [NSDate date]]; 

這行代碼將當前日期設置爲可以在選擇器中選擇的最大日期。

+0

不知道我理解你的第一條評論,我理解爲「......完全意思。」這是什麼意思?還有什麼值增加了其他答案?其他答案肯定已經提供了你的答案已經說明了什麼? – Popeye 2016-01-05 09:11:19

+0

嗨Popeye感謝您的意見 – 2016-01-05 09:15:40

+0

忘記我以前的評論的最後一部分,事實是你的有什麼正在發生的增加價值,因爲其他人沒有任何東西。 +1就是爲了這個。 – Popeye 2016-01-05 09:16:14