iOS 年月pickView数据源获取

1.一维数组:yyyy-MM

//数据获取
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
        //当前日期时间
        NSDate *currentDate = [NSDate date];
        //设定数据格式为xxxx-mm
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM"];
        //通过日历可以直接获取前几个月的日期,所以这里直接用该类的方法进行循环获取数据
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
        NSString *dateStr = [formatter stringFromDate:currentDate];
        NSInteger lastIndex = 0;
        NSDate *newdate;
        NSString *minDateStr = @"2019-01";
        //循环获取可选月份,从当前月份到最小月份,直接用字符串的比较来判断是否大于设定的最小日期
        while (!([dateStr compare:minDateStr] == NSOrderedAscending)) {
            [_dataArray addObject:dateStr];
            lastIndex--;
            //获取之前n个月, setMonth的参数为正则向后,为负则表示之前
            [lastMonthComps setMonth:lastIndex];
            newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
            dateStr = [formatter stringFromDate:newdate];
        }
    }
    return _dataArray;
}

2.二维数组

- (NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        NSString *currentMonth = @"";
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
        fmt.dateFormat = @"yyyy-MM";
        fmt.timeZone = [NSTimeZone localTimeZone];
        fmt.locale = [NSLocale currentLocale];
        
        NSString *minDateStr = @"2015-09";
        NSString *maxDateStr = @"2017-04";
        //NSString *minDateStr = @"2019/01";
        //NSString *maxDateStr = [fmt stringFromDate:[NSDate date]];
        NSDate *date = [fmt dateFromString:maxDateStr];
        
        NSMutableArray *yearMonthList = [NSMutableArray array];
        int i = 0;
        // 循环,月份递减,直到年月等于最小值即可
        // 注意:循环退出条件,避免死循环!
        do {
            NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
            NSDateComponents *adcomps = [[NSDateComponents alloc]init];
            [adcomps setYear:0];
            // 因为这里需要包含最大月份,所以需要这个判断
            adcomps.month = i == 0 ? 0 : -1;
            i += 1;
            
            date = [calendar dateByAddingComponents:adcomps toDate:date options:0];
            currentMonth = [fmt stringFromDate:date];
            if (i > 100 ){
                NSLog(@"可能是死循环,手动跳出循环");
                break;
            }
            [yearMonthList addObject:currentMonth];
            
        } while ([currentMonth compare: minDateStr] == NSOrderedDescending);
        
        
        // 存储处理后的数据集
        NSMutableArray *resultList = [NSMutableArray array];
        // 存储年月数据对象(year-months)
        YearDayModel *yearModel = [[YearDayModel alloc]init];
        // 存储该 year 中包含的所有 month
        NSMutableArray *monthTmpList = [NSMutableArray array];
        for (NSString *YMStr in yearMonthList) {
            NSArray *tmpList = [YMStr componentsSeparatedByString:@"-"];
            NSString *year = tmpList.firstObject;
            NSString *month = tmpList.lastObject;
            if ([yearModel.year isEqualToString:year]) {
                // 当前 year 在 resultList 中已存储,局部变量不需要初始化
            }else{
                // 当前 year 在 resultList 中未存储,是新的年份,所以需要对部分变量初始化!
                [monthTmpList removeAllObjects];
                yearModel = [[YearDayModel alloc]init];
                yearModel.year = year;
            }
            [monthTmpList addObject:month];
            yearModel.months = monthTmpList;
            
            // 去除月份不“完整”的数据,最后只会保留该 year 中,month 最完整的那条记录
            [resultList enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(YearDayModel *  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
                NSArray *currentObj = model.months;
                if (currentObj.count > 0) {
                    if (model.year == yearModel.year) {
                        [resultList removeObject:model];
                    }
                }
            }];
            
            [resultList addObject:yearModel];
        }
        _dataSource = resultList;
    }
    
    //NSLog(@"%@",_dataSource);
    return _dataSource;   
}

Model:

#import "BaseModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface YearDayModel : BaseModel
@property (nonatomic,copy)NSString *year;
@property (nonatomic,copy)NSArray *months;
@end

NS_ASSUME_NONNULL_END

使用:

@property (strong,nonatomic)NSMutableArray *dataSource;//年月数据源
@property (assign,nonatomic)NSInteger indexY;//选择了年的index
#pragma mark - UIPickerView
// 返回选择器有几列.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

// 返回每组有几行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        
        case 0:
            return self.dataSource.count;
            break;
            
        case 1:{
            if (self.dataSource.count == 0 ){  return 0; }
            YearDayModel *model = self.dataSource[self.indexY];
            return model.months.count;
        }
            break;
            
        default:
            break;
    }
    return 0;
}

// 返回第component列第row行的内容(标题)
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    switch (component) {
            
        case 0:{
            YearDayModel *model = self.dataSource[row];
            return [model.year stringByAppendingString:@"年"];
        }
            break;
            
        case 1:{
            YearDayModel *model = self.dataSource[self.indexY];
            NSArray *months = model.months;
            return [months[row] stringByAppendingString:@"月"];
        }
            break;
            
        default:
            break;
    }
    return nil;
}


- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 36;
}

// 设置row字体,颜色
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    UILabel* pickerLabel            = (UILabel*)view;
    
    if (!pickerLabel){
        pickerLabel                 = [[UILabel alloc]init];
        pickerLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment   = NSTextAlignmentCenter;
        pickerLabel.backgroundColor = [UIColor clearColor];
        pickerLabel.font            = font(24);
        pickerLabel.textColor       = [UIColor blackColor];//colorWithHex:0x222222
    }
    
    pickerLabel.text                = [self pickerView:pickerView titleForRow:row forComponent:component];
    
    return pickerLabel;
}

// 选中第component第row的时候调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:{
            self.indexY = [pickerView selectedRowInComponent:0];
            [self.YMpickView reloadComponent:1];
        }
            break;
        case 1:{
          //自动显示
            if (self.dataSource.count == 0) {return;}
            YearDayModel *model = self.dataSource[self.indexY];
            NSString *month =  model.months[row];
            NSString *time = [NSString stringWithFormat:@"%@-%@",model.year,month];
            self.monthTF.text = time;
        }
            break;
            
        default:
            break;
    }
}

=========================================

UIDatePicker 停止滚动时候,自动显示

// 滚动改变值的响应事件
     [self.YMDPickView addTarget:self action:@selector(didSelectValueChanged:) forControlEvents:UIControlEventValueChanged];
#pragma mark - 时间选择器的滚动响应事件
 - (void)didSelectValueChanged:(UIDatePicker *)sender {
     // 读取日期:datePicker.date
     self.selectDate = sender.date;
 
     BOOL selectLessThanMin = [self.selectDate br_compare:self.minLimitDate format:self.selectDateFormatter] == NSOrderedAscending;
     BOOL selectMoreThanMax = [self.selectDate br_compare:self.maxLimitDate format:self.selectDateFormatter] == NSOrderedDescending;
     if (selectLessThanMin) {
     self.selectDate = self.minLimitDate;
     }
     if (selectMoreThanMax) {
     self.selectDate = self.maxLimitDate;
     }
     [self.datePicker setDate:self.selectDate animated:YES];
 
     NSString *selectDateValue = [NSDate br_getDateString:self.selectDate format:self.selectDateFormatter];
 }

你可能感兴趣的:(iOS 年月pickView数据源获取)