显示具有null年份值的UIDatePicker

时间:2014-01-11 14:50:55

标签: ios uidatepicker

我在我的应用程序中使用UIDatePicker与UIDatePickerModeDate。我想使用与iOS联系地址簿中相同的DatePicker样式,您可以在其中设置日期而不是年份:

September | 11 | 2014
October | 12 | ----
November | 13 |

在textField中获取字符串:October 12

有什么想法吗?

enter image description here

2 个答案:

答案 0 :(得分:1)

只需添加UIPickerView(NOT UIDatePickerView)并将Datasource(和委托)设置为您的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)];
        }
}

结果如下所示: resulting PickerView

您可以实施

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component 

为了改变每个组件的宽度。

答案 1 :(得分:0)

UIDatepickerModeDate不会让您获得所需的日期格式。因此要么是用户UIPickerView&定制它有日期,否则,按照上面的答案。

此外,您可能有兴趣阅读此内容。

link 1

希望有所帮助。