objective-c - 有没有办法删除日期选择器的 "year"?

标签 objective-c ios cocoa-touch

我在 View 中有一个日期选择器,但我只希望它显示日期和月份,而不是年份,有没有办法去掉年份?

最佳答案

正如其他人所指出的:您需要一个人来创建自己的选择器,但实际上这并不困难。一个快速原型(prototype),请注意,我使用第一个组件几天,第二个组件多年,这应该根据真实世界应用程序中的语言环境来制作:

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

-(NSInteger)pickerView:pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSUInteger number = 0;
    if (component == 1) {
        number = 12;
    } else {

        NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];

        NSUInteger month = [pickerView selectedRowInComponent:1]+1 ;
        NSUInteger actualYear = [comps year];

        NSDateComponents *selectMothComps = [[NSDateComponents alloc] init];
        selectMothComps.year = actualYear;
        selectMothComps.month = month;
        selectMothComps.day = 1;

        NSDateComponents *nextMothComps = [[NSDateComponents alloc] init];
        nextMothComps.year = actualYear;
        nextMothComps.month = month+1;
        nextMothComps.day = 1;

        NSDate *thisMonthDate = [[NSCalendar currentCalendar] dateFromComponents:selectMothComps];
        NSDate *nextMonthDate = [[NSCalendar currentCalendar] dateFromComponents:nextMothComps];

        NSDateComponents *differnce = [[NSCalendar currentCalendar]  components:NSDayCalendarUnit
                                                   fromDate:thisMonthDate
                                                     toDate:nextMonthDate
                                                    options:0];

        number = [differnce day];

    }

    return number;
}

-(void)pickerView:pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 1) {
        [pickerView reloadComponent:0];
    }
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [NSString stringWithFormat:@"%d", row+1];
}

您可以在 GitHub 找到示例代码


您在 GitHub 上找到的版本知道最喜欢的语言的月份名称

enter image description here

关于objective-c - 有没有办法删除日期选择器的 "year"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13169602/

相关文章:

objective-c - 带有自动布局的 iOS8 UITableView 在单元格上方有一个空白区域

ios - Swift - 如何禁止初始化程序?

ios - 如何更新之前在代码中设置的 NSLayoutConstraint 常量? - swift

ios - UIApplication中的窗口和AppDelegate中的窗口是什么关系?

ios - 从其他类访问 UI 元素

ios - Objective-C GET 请求 - 如何不卡住 UI 并等待响应?

objective-c - UICollectionView 断言失败

ios - MPMediaItem的数据大小(Objective-C)

iphone - activityIndi​​catorViewStyle 只能设置一次?

ios - UICollectionView 在 iOS 7 上运行时不显示