[英]Showing a UIDatePicker with a null Year value
我在應用程序中使用UIDatePickerModeDate使用UIDatePicker。 我想使用與iOS聯系人通訊錄中相同的DatePicker樣式,您可以在其中設置不帶年份的日期:
September | 11 | 2014
October | 12 | ----
November | 13 |
在textField中獲取字符串: October 12
有任何想法嗎?
只需添加一個UIPickerView(NOT UIDatePickerView)並將數據源(和委托)設置為您的Class。 然后在您的課程中添加以下內容:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (component) {
case 0: // how many days? (you might find out how many days the month really had, instead of just returning 31
{
#if TARGET_IPHONE_SIMULATOR
return 50000;
// I don't now, what the exact Value for NSIntegerMax is, but 50000 should be enough for testing.
#else
return NSIntegerMax;
#endif
break;
}
case 1: // how many months to display?
{
#if TARGET_IPHONE_SIMULATOR
return 50000;
#else
return NSIntegerMax;
#endif
break;
}
case 2:
{
return 100; // how many years?
break;
}
}
return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0) // days
return [NSString stringWithFormat:@"%i",(int)row % 31 + 1];
else if (component == 1) // month
{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%i",(int)row % 12 + 1]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
return [formatter stringFromDate:myDate];
}
else if (component == 2 && row == ([pickerView numberOfRowsInComponent:2] - 1))
return @"-----";
else
{
// let's use NSDateFormatter to get the current year:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY"];
return [NSString stringWithFormat:@"%i",[[dateFormatter stringFromDate:[NSDate date]] integerValue] - ([pickerView numberOfRowsInComponent:2] - 1) + (row + 1)];
}
}
結果如下:
您可以實施
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
為了更改每個組件的寬度。
UIDatepickerModeDate不會讓您獲得所需的日期格式。 因此,要么使用UIPickerView並自定義日期,要么按照上面的答案進行操作。
您也可以對閱讀此書感興趣。
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.