iOS自定义时间PickerView

作为日常开发记录

iOS自定义时间PickerView_第1张图片
IMG_6CC60D197C20-1.jpeg
//YDDXDatePickerView.h

@class YDDXDatePickerView;
@protocol YDDXDatePickerViewDelegate 

- (void)YDDXDatePickerView:(YDDXDatePickerView *)pickerView chooseDateString:(NSString *)dateString;

@end

@interface YDDXDatePickerView : UIView

@property (nonatomic, weak) id delegate;
@end
//YDDXDatePickerView.m
@interface YDDXDatePickerView ()
{
    NSInteger yearIndex;

    NSInteger monthIndex;

    NSInteger dayIndex;
}

@property (nonatomic, strong) UIPickerView *pickerView;

//data
@property (nonatomic, strong) NSMutableArray *yearArray;
@property (nonatomic, strong) NSMutableArray *monthArray;
@property (nonatomic, strong) NSMutableArray *dayArray;

@end

@implementation YDDXDatePickerView

- (instancetype)init {
    if (self = [super init]) {
        [self setupView];
        [self pickerViewSelectedDateForCurrent];
    }
    return self;
}

#pragma mark - UIPickerViewDelegate&DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.yearArray.count;
        
    } else if(component == 1) {
        
        return self.monthArray.count;
        
    } else {
        
        switch (monthIndex + 1) {
                
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12: return 31;
                
            case 4:
            case 6:
            case 9:
            case 11: return 30;
                
            default: return 28;
        }
    }
}

// 滚动UIPickerView就会调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        
        yearIndex = row;
        
        UILabel *label = (UILabel *)[pickerView viewForRow:row forComponent:component];
        label.textColor = COLOR_LABEL_TEXT;
        label.font = BOLDSYSTEMFONT(16.f);
        
        
    } else if (component == 1) {
        
        monthIndex = row;
        [pickerView reloadComponent:2];
        
        if (monthIndex + 1 == 4 || monthIndex + 1 == 6 || monthIndex + 1 == 9 || monthIndex + 1 == 11) {
            if (dayIndex + 1 == 31) {
                dayIndex--;
            }
        }else if (monthIndex + 1 == 2) {
            if (dayIndex + 1 > 28) {
                dayIndex = 27;
            }
        }
        
        [pickerView selectRow:dayIndex inComponent:2 animated:YES];
        
        UILabel *label = (UILabel *)[pickerView viewForRow:row forComponent:component];
        label.textColor = COLOR_LABEL_TEXT;
        label.font = BOLDSYSTEMFONT(16.f);
        
        label = (UILabel *)[pickerView viewForRow:dayIndex forComponent:2];
        label.textColor = COLOR_LABEL_TEXT;
        label.font = BOLDSYSTEMFONT(16.f);
              
    } else {
        
        dayIndex = row;
        
        UILabel *label = (UILabel *)[pickerView viewForRow:row forComponent:component];
        label.textColor = COLOR_LABEL_TEXT;
        label.font = BOLDSYSTEMFONT(16.f);
        
        
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = [[UILabel alloc] init];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = COLOR_LABEL_TEXT;
    label.font = BOLDSYSTEMFONT(16.f);
    if (component == 0) {
        label.text = self.yearArray[row];
    } else if (component == 1) {
        label.text = self.monthArray[row];
    } else {
        label.text = self.dayArray[row];
    }
    
    return label;
}

#pragma mark - private
- (void)setupView {
 
    UIView *topView = [[UIView alloc] init];
    UIColor *bgColor;
    if (@available(iOS 13, *)) {
        bgColor = [UIColor xy_createWithLightColor:[UIColor whiteColor] darkColor:[UIColor secondarySystemBackgroundColor]];
    } else {
        bgColor = [UIColor whiteColor];
    }
    topView.backgroundColor = bgColor;
    [self addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(40);
    }];
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    CGRect rect = topView.frame;
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, rect.size.width, rect.size.height) byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(5, 5)].CGPath;
    topView.layer.mask = maskLayer;
    topView.layer.masksToBounds = YES;
    
    UILabel *topViewLeftLbl = [[UILabel alloc] init];
    topViewLeftLbl.text = @"选择时间";
    topViewLeftLbl.textColor = COLOR_LABEL_TEXT;
    topViewLeftLbl.font = BOLDSYSTEMFONT(16);
    [topView addSubview:topViewLeftLbl];
    [topViewLeftLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(0);
    }];
    
    UIButton *closeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [closeButton setImage:[UIImage imageNamed:@"common_close"] forState:(UIControlStateNormal)];
    [closeButton addTarget:self action:@selector(closeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [topView addSubview:closeButton];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.mas_equalTo(0);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = COLOR_LINE_AUTO;
    [topView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    
    [self addSubview:self.pickerView];
    [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(topView.mas_bottom);
        make.height.mas_equalTo(SCREEN_HEIGHT/3);
    }];
    
    UIView *buttonView = [[UIView alloc] init];
    [self addSubview:buttonView];
    [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(50.f);
        make.top.equalTo(self.pickerView.mas_bottom);
    }];
    
    UIButton *cleanButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [cleanButton setTitle:@"清除" forState:(UIControlStateNormal)];
    [cleanButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [cleanButton.titleLabel setFont:BOLDSYSTEMFONT(15.f)];
    [cleanButton setBackgroundColor:COLOR_BG_GRAY];
    [cleanButton addTarget:self action:@selector(cleanAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [buttonView addSubview:cleanButton];
    [cleanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH*1/3);
    }];
    
    UIButton *confirmButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [confirmButton setTitle:@"确定" forState:(UIControlStateNormal)];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [confirmButton.titleLabel setFont:BOLDSYSTEMFONT(15.f)];
    [confirmButton setBackgroundColor:COLOR_THEME];
    [confirmButton addTarget:self action:@selector(confirmAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [buttonView addSubview:confirmButton];
    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cleanButton.mas_right);
        make.top.right.bottom.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH*2/3);
    }];
}

- (void)pickerViewSelectedDateForCurrent {
    NSCalendar *calendar = [[NSCalendar alloc]
                            initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents *comp = [calendar components: unitFlags fromDate:[NSDate date]];

    yearIndex = [self.yearArray indexOfObject:[NSString stringWithFormat:@"%ld年", comp.year]];
    monthIndex = [self.monthArray indexOfObject:[NSString stringWithFormat:@"%02ld月", comp.month]];
    dayIndex = [self.dayArray indexOfObject:[NSString stringWithFormat:@"%02ld日", comp.day]];

    [_pickerView selectRow:yearIndex inComponent:0 animated:YES];
    [_pickerView selectRow:monthIndex inComponent:1 animated:YES];
    [_pickerView selectRow:dayIndex inComponent:2 animated:YES];

    [self pickerView:_pickerView didSelectRow:yearIndex inComponent:0];
    [self pickerView:_pickerView didSelectRow:monthIndex inComponent:1];
    [self pickerView:_pickerView didSelectRow:dayIndex inComponent:2];
}

#pragma mark - action
- (void)closeAction:(UIButton *)sender {
    [[KYSAlertManager sharedManager] hideCustomAlertView];
}

- (void)confirmAction:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(YDDXDatePickerView:chooseDateString:)]) {
        NSString *yearString;
        NSString *monthString;
        if (self.yearArray.count > yearIndex) {
            yearString = self.yearArray[yearIndex] ?: @"";
        }
        if (self.monthArray.count > monthIndex) {
            monthString = self.monthArray[monthIndex] ?: @"";
        }
        [self.delegate YDDXDatePickerView:self chooseDateString:[NSString stringWithFormat:@"%@-%@",yearString,monthString]];
    }
}

- (void)cleanAction:(UIButton *)sender {
    [self pickerViewSelectedDateForCurrent];
}

#pragma mark - getter
- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] init];
        UIColor *bgColor;
        if (@available(iOS 13, *)) {
            bgColor = [UIColor xy_createWithLightColor:[UIColor whiteColor] darkColor:[UIColor secondarySystemBackgroundColor]];
        } else {
            bgColor = [UIColor whiteColor];
        }
        _pickerView.backgroundColor = bgColor;
        _pickerView.dataSource = self;
        _pickerView.delegate = self;
    }
    return _pickerView;
}

- (NSMutableArray *)yearArray {
    if (!_yearArray) {
        _yearArray = [NSMutableArray array];
        for (int year = 2000; year < 2050; year++) {
            NSString *str = [NSString stringWithFormat:@"%d年", year];
            [_yearArray addObject:str];
        }
    }
    return _yearArray;
}

- (NSMutableArray *)monthArray {
    if (!_monthArray) {
        _monthArray = [NSMutableArray array];
        for (int month = 1; month <= 12; month++) {
            NSString *str = [NSString stringWithFormat:@"%02d月", month];
            [_monthArray addObject:str];
        }
    }
    return _monthArray;
}

- (NSMutableArray *)dayArray {
    if (!_dayArray) {
        _dayArray = [NSMutableArray array];
        for (int day = 1; day <= 31; day++) {
            NSString *str = [NSString stringWithFormat:@"%02d日", day];
            [_dayArray addObject:str];
        }
    }
    return _dayArray;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

你可能感兴趣的:(iOS自定义时间PickerView)