PickerView的使用(详图)

项目实现的效果如下:

datepicker04.gif

对实现细节的要求有:
1开始日期默认选中上个月的第一天,结束日期选中今天;
2显示最近13个月,每月日期个数随月份变化;
3确定时,开始日期不能大于结束日期;
具体实现思路,用NSCalendar获取今天的月份,以此月份为基础,获取前一年的各月,并计算出各月的日期数.在选中月份时,对日期进列的个数进行更新.代码如下:

- (instancetype)init
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [okBtn setTitle:@"确定" forState:UIControlStateNormal];
        okBtn.backgroundColor = [UIColor grayColor];
        [self addSubview:okBtn];
        [okBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(@0);
            make.height.equalTo(@44);
        }];
        okBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [okBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [okBtn addTarget:self action:@selector(okBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        self.firstRowCount = 15;
        self.secondRowCount = 15;
        UIPickerView *pickV = [[UIPickerView alloc] init];
        self.pickV = pickV;
        pickV.backgroundColor = [UIColor whiteColor];
        pickV.dataSource = self;
        pickV.delegate = self;
        [self addSubview:pickV];
        [pickV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.left.equalTo(@0);
            make.height.equalTo(@150);
            make.bottom.equalTo(okBtn.mas_top);
        }];

        UIView *topV = [[UIView alloc] init];
        topV.backgroundColor = [UIColor grayColor];
        UILabel *leftL = [GXHoldTool labelWithWeight:1 font:16 text:@"开始日期" textColor:[UIColor blueColor]];
        leftL.textAlignment = NSTextAlignmentCenter;
        UILabel *rightL = [GXHoldTool labelWithWeight:1 font:16 text:@"结束日期" textColor:[UIColor blueColor]];
        rightL.textAlignment = NSTextAlignmentCenter;
        [topV addSubview:leftL];
        [topV addSubview:rightL];
        [leftL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(@0);
            make.left.equalTo(@0);
            make.width.equalTo(@(GXScreenWidth / 2));
        }];
        [rightL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(@0);
            make.right.equalTo(@0);
            make.width.equalTo(@(GXScreenWidth / 2));
        }];
        [self addSubview:topV];
        [topV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(@0);
            make.height.equalTo(@40);
            make.bottom.equalTo(pickV.mas_top);
        }];
        [pickV selectRow:(self.dataSource.firstObject.count - 2) inComponent:0 animated:true];
        [pickV selectRow:0 inComponent:1 animated:true];
        [pickV selectRow:(self.dataSource.lastObject.count - 1) inComponent:2 animated:true];
        [pickV selectRow:(self.secondRowCount - 1) inComponent:3 animated:true];
    }
    return self;
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 4;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSInteger row;
    if (component == 0) {
        row = self.dataSource.firstObject.count;
    }else if(component == 1){
        row = self.firstRowCount;
    }else if(component == 2){
        row = self.dataSource.lastObject.count;
    }else if(component == 3){
        row = self.secondRowCount;
    }
    return row;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self removeFromSuperview];
}
#pragma mark - UIPickerViewDelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view{
    UILabel *label = [[UILabel alloc] init];

    NSString *title;
    if (component == 0) {
        title = self.dataSource.firstObject[row];
    }else if(component == 1 || component == 3){
        title = self.daysArray[row];
        NSString *str = [NSString stringWithFormat:@"%@%@", self.seletedMonthStr, title];
        //        GXLog(@"%@", str);
        NSDateFormatter *dateF = [NSDateFormatter shareFormatter];
        dateF.dateFormat = @"yyyy年MM月dd日";
        NSDate *date = [dateF dateFromString:str];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        if ([calendar isDateInToday:date]) {
            title = @"今天";
        }
    }else if(component == 2){
        title = self.dataSource.lastObject[row];
        self.seletedMonthStr = title;
    }
    
    label.text = title;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14];
    return label;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        NSArray *monthArr = self.dataSource[0];
        NSString *monthStr = monthArr[row];
        self.seletedMonthStr = monthStr;
        self.firstRowCount = [self daysCount:monthStr];
        if (row == monthArr.count - 1) {
            NSCalendar *calendar = [NSCalendar currentCalendar];
            self.firstRowCount = [calendar component:NSCalendarUnitDay fromDate:[NSDate date]];
        }
        [pickerView reloadComponent:1];
    }
    else if (component == 2){
        NSArray *monthArr = self.dataSource[1];
        NSString *monthStr = monthArr[row];
        self.seletedMonthStr = monthStr;
        self.secondRowCount = [self daysCount:monthStr];
        if (row == monthArr.count - 1) {
            NSCalendar *calendar = [NSCalendar currentCalendar];
            self.secondRowCount = [calendar component:NSCalendarUnitDay fromDate:[NSDate date]];
        }
        [pickerView reloadComponent:3];
    }
}

- (NSInteger)daysCount: (NSString *)dateStr{
    NSDateFormatter *dateF = [NSDateFormatter shareFormatter];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    dateF.dateFormat = @"yyyy年MM月";
    NSDate *date = [dateF dateFromString:dateStr];
    NSRange days = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return days.length;
}

- (void)okBtnClick{
    NSInteger first = [self.pickV selectedRowInComponent:0];
    NSInteger second = [self.pickV selectedRowInComponent:1];
    NSInteger third = [self.pickV selectedRowInComponent:2];
    NSInteger forth = [self.pickV selectedRowInComponent:3];
    NSString *beginDateStr = [NSString stringWithFormat:@"%@%@", self.dataSource.firstObject[first], self.daysArray[second]];
    NSString *endDateStr = [NSString stringWithFormat:@"%@%@", self.dataSource.firstObject[third], self.daysArray[forth]];
    NSDateFormatter *dateF = [NSDateFormatter shareFormatter];
    dateF.dateFormat = @"yyyy年MM月dd日";
    NSDate *beginDate = [dateF dateFromString:beginDateStr];
    NSDate *endDate = [dateF dateFromString:endDateStr];
    NSTimeInterval dateInterval = [beginDate timeIntervalSinceDate:endDate];
    if (dateInterval >= 0) {
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"开始日期不能大于结束日期,请您重新选择" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertV show];
    }
    
}

-(NSArray *)dataSource{
    if (!_dataSource) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:2];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSInteger year = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
        NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:[NSDate date]];
        NSMutableArray *arrMOne = [NSMutableArray arrayWithCapacity:13];
        year = year - 1;
        for (int j = 0; j < 13; j++) {
            if (month > 12) {
                month = 1;
                year += 1;
            }
            NSString *dateOne = [NSString stringWithFormat:@"%zd年%02zd月",year, month];
            [arrMOne addObject:dateOne];
            month++;
        }
        [arrM addObject:arrMOne];
        [arrM addObject:arrMOne.copy];
        
        _dataSource = arrM;
    }
    
    return _dataSource;
}

- (NSArray *)daysArray{
    if (!_daysArray) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:31];
        for (int i = 0; i < 31; i++) {
            NSString *dayStr = [NSString stringWithFormat:@"%02zd日", i+1];
            [arrM addObject:dayStr];
        }
        _daysArray = arrM;
    }
    return _daysArray;
}

当然,过程中也遇到一些坑,如下图:

datepicker01.gif

项目中是通过返回各个compoment的UILabel来实现日期和列,但是月份列显示倾斜,不受控制,调整UILabel的NSTextAlignment属性无果.
反复试验,不实现UIPickerViewDelegate的以下两个方法可以解决:

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
}

个人估计原因,实现以上两个方法后,系统会自动生成显示区域,不受返回的UIView控制,也有可能是pickerView自身存在的bug(就像你知道的DatePicker性能低下一般).
希望遇到以上问题的小伙伴参照后,能顺利解决~

Demo

喜欢和收藏都是对我的鼓励和支持

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352

推荐阅读更多精彩内容