首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >显示年份值为空的UIDatePicker

显示年份值为空的UIDatePicker
EN

Stack Overflow用户
提问于 2014-01-11 22:50:55
回答 2查看 1.8K关注 0票数 1

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

代码语言:javascript
运行
复制
September | 11 | 2014
October | 12 | ----
November | 13 |

获取textField中的字符串:October 12

有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2014-01-11 23:49:27

只需添加一个UIPickerView (而不是UIDatePickerView),并将数据源(和委托)设置为您的类。然后在你的类中添加类似这样的内容:

代码语言:javascript
运行
复制
- (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)];
        }
}

结果如下所示:

您可以实现

代码语言:javascript
运行
复制
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component 

以便更改每个组件的宽度。

票数 1
EN

Stack Overflow用户

发布于 2014-01-12 02:46:44

UIDatepickerModeDate不会让您获得所需的日期格式。因此,要么使用UIPickerView & customize it got,要么遵循上面答案中的技巧。

你也可以对阅读这篇文章感兴趣。

link 1

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21063676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档