日期选择器(仿比心)

话不多说,贴上代码

//
//  MLTimePickerView.h
//  MaryDemo
//
//  Created by 玛丽 on 2019/11/18.
//  Copyright © 2019 玛丽. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN
@protocol TimePickerViewDelegate<NSObject>
@optional
-(void)timePickerViewDidSelectRowWithTime:(NSString *)timeStr withTimeStamp:(NSString *)timeStamp;
@end

@interface MLTimePickerView : UIView
@property (nonatomic, weak) id<TimePickerViewDelegate> delegate;
- (instancetype)initWithTimePickerView;
- (void)show;
- (void)dismiss;
@end

NS_ASSUME_NONNULL_END
//
//  MLTimePickerView.m
//  MaryDemo
//
//  Created by 玛丽 on 2019/11/18.
//  Copyright © 2019 玛丽. All rights reserved.
//

#import "MLTimePickerView.h"

#define ml_ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ml_ScreenHeight [UIScreen mainScreen].bounds.size.height

@interface MLTimePickerView()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic, strong)UIPickerView *pickerView;
@property (nonatomic, strong)UIView *backView;
@property (nonatomic, strong)UIButton *cancelButton;
@property (nonatomic, strong)UIButton *sureButton;
@property (nonatomic, strong)UILabel *titleLabel;
@property (nonatomic, strong)UILabel *detailTitleLabel;

@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)NSMutableArray *weekArray;
@property (nonatomic, strong)NSMutableArray *minuteArray;
@property (nonatomic, strong)NSArray *mArray;
@property (nonatomic, strong)NSMutableArray *hArray;//24小时制
@property (nonatomic, strong)NSMutableArray *dhArray;//当天之后小时
@property (nonatomic, strong)NSString *timeStr;
@property (nonatomic, assign)BOOL isToday;
@property (nonatomic, assign)NSInteger m_hours;
@property (nonatomic, assign)NSInteger m_minute;
@end

@implementation MLTimePickerView

- (instancetype)initWithTimePickerView{
    if (self = [super init]) {
        self.frame = [UIScreen mainScreen].bounds;
        [self setupView];
    }
    return self;
}

- (void)setupView{
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self addSubview:self.backView];
    [self.backView addSubview:self.cancelButton];
    [self.backView addSubview:self.sureButton];
    [self.backView addSubview:self.titleLabel];
    [self.backView addSubview:self.detailTitleLabel];
    [self.backView addSubview:self.pickerView];
    self.isToday = true;
    
    NSArray *oneArr = @[@"今天", @"明天", @"后天"];
    self.mArray = @[@"00", @"15", @"30", @"45"];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute)  fromDate:[NSDate date]];
    
    NSInteger year = [comps year];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSInteger hours = [comps hour];
    NSInteger minute = [comps minute];
    
    for (NSString *str in self.mArray) {
        if ([str integerValue] > minute) {
            [self.minuteArray addObject:str];
        }
    }

    [self.dhArray addObject:@"现在"];
    for (int i = self.minuteArray.count == 0 ? (int)hours+1 : (int)hours; i < 24; i++) {
        [self.dhArray addObject:[NSString stringWithFormat:@"%02d", i]];
    }
    for (int i = 0; i < 24; i++) {
        [self.hArray addObject:[NSString stringWithFormat:@"%02d", i]];
    }
    [self.dataArray addObject:oneArr];
    [self.dataArray addObject:self.dhArray];
    [self.dataArray addObject:@[]];
    
    self.timeStr = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld", year, month, day, hours, minute];
}

#pragma mark - UIPickerViewDataSource UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return [self.dataArray count];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.dataArray[component] count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return self.dataArray[component][row];
}

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

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    [self.dataArray removeObjectAtIndex:2];
    if (component != 0) {
        if (component == 1 && row == 0) {
            if (self.isToday) {
                [self.dataArray addObject:@[]];
            } else {
                [self.dataArray addObject:self.mArray];
            }
        } else if (component == 1 && row == 1 && self.minuteArray.count != 0) {
            if (self.isToday) {
                [self.dataArray addObject:self.minuteArray];
            } else {
                [self.dataArray addObject:self.mArray];
            }
        } else {
            [self.dataArray addObject:self.mArray];
        }
    } else {
        [self.dataArray addObject:row == 0 ? @[] : self.mArray];
    }
    [self.pickerView reloadComponent:2];
    
    NSDate *date= [self getTimeAfterNowWithDay:0];;
    if (component == 0) {
        date= [self getTimeAfterNowWithDay:row];
        if (row == 0) {
            [self.dataArray removeObjectAtIndex:1];
            [self.dataArray insertObject:self.dhArray atIndex:1];
            self.isToday = true;
        } else {
            [self.dataArray removeObjectAtIndex:1];
            [self.dataArray insertObject:self.hArray atIndex:1];
            self.isToday = false;
        }
        [self.pickerView selectRow:0 inComponent:1 animated:YES];
        [self.pickerView selectRow:0 inComponent:2 animated:YES];
        [self.pickerView reloadComponent:1];
        [self.pickerView reloadComponent:2];
    }
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:date];
    NSInteger year = [components year];
    NSInteger month = [components month];
    NSInteger day = [components day];
    NSInteger hours = [components hour];
    NSInteger minute = [components minute];
    if (component == 0) {
        if (!self.isToday) {
            self.m_hours = hours = 0;
            self.m_minute = minute = 0;
        }
    } else if (component == 1) {
        if ((self.isToday && row > 0 && [self.dataArray[2] count] != 0) || (!self.isToday && [self.dataArray[2] count] != 0)) {
            self.m_hours = hours = [self.dataArray[1][row] integerValue];
            minute = self.m_minute;
            if (row == 1) {
                minute = [self.dataArray[2][0] integerValue];
            }
        }
    } else if (component == 2) {
        if ([self.dataArray[2] count] != 0) {
            hours = self.m_hours;
            self.m_minute = minute = [self.dataArray[2][row] integerValue];
        }
    }
    self.timeStr = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld", year, month, day, hours, minute];
    NSLog(@"%ld-%ld-%ld %ld:%ld", year, month, day, hours, minute);
}



- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    if (component == 0) {
        UIView *pNode = view;
        if (!pNode) {
            pNode = [[UIView alloc] init];
            UILabel *pickerLabel = [[UILabel alloc] init];
            pickerLabel.font = [UIFont systemFontOfSize:15];
            pickerLabel.textAlignment = NSTextAlignmentRight;
            pickerLabel.textColor = [UIColor blackColor];
            pickerLabel.frame = CGRectMake(0, 0, ml_ScreenWidth/6, 35);
            [pNode addSubview:pickerLabel];
            UILabel *detailLabel = [[UILabel alloc] init];
            detailLabel.font = [UIFont systemFontOfSize:11];
            detailLabel.textAlignment = NSTextAlignmentCenter;
            detailLabel.textColor = [UIColor blueColor];
            detailLabel.backgroundColor = [UIColor groupTableViewBackgroundColor];
            detailLabel.frame = CGRectMake(ml_ScreenWidth/6+8, 7.5, 35, 20);
            detailLabel.layer.masksToBounds = YES;
            detailLabel.layer.cornerRadius = 3.f;
            [pNode addSubview:detailLabel];
            detailLabel.text = self.weekArray[row];
            pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
        }
        return pNode;
    } else {
        UILabel* pickerLabel = (UILabel*)view;
        if (!pickerLabel) {
            pickerLabel = [[UILabel alloc] init];
            pickerLabel.font = [UIFont systemFontOfSize:15];
            pickerLabel.textAlignment = NSTextAlignmentCenter;
            pickerLabel.textColor = [UIColor blackColor];
        }
        pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
        return pickerLabel;
    }
}

#pragma mark - 事件
- (void)cancelButtonAction{
    [self dismiss];
}

- (void)sureButtonAction{
    NSString *timeStamp = [NSString stringWithFormat:@"%ld", [self timeSwitchTimestamp:self.timeStr andFormatter:@"YYYY-MM-dd HH:mm"]];
    if ([self.delegate respondsToSelector:@selector(timePickerViewDidSelectRowWithTime:withTimeStamp:)]) {
        [self.delegate timePickerViewDidSelectRowWithTime:self.timeStr withTimeStamp:timeStamp];
        [self dismiss];
    }
}

- (void)show{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:0.4 animations:^{
        self.backView.center = CGPointMake(ml_ScreenWidth/2, self.backView.center.y - self.backView.frame.size.height);
    }];
}

- (void)dismiss{
    [UIView animateWithDuration:0.4 animations:^{
        self.backView.center = CGPointMake(ml_ScreenWidth/2, self.backView.center.y + self.backView.frame.size.height);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - 得到当前时间之后N天的日期
- (NSDate *)getTimeAfterNowWithDay:(NSInteger)day {
    NSDate *nowDate = [NSDate date];
    NSDate *theDate;
    if(day!=0) {
        NSTimeInterval  oneDay = 24*60*60*1;
        theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*day];
    } else {
        theDate = nowDate;
    }
    return theDate;
}

#pragma mark - 将某个时间转化成 时间戳
-(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:formatTime];
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
}

#pragma mark - 获取后续三天是周几
- (NSArray *)weekdayArray {
    NSDate *date = [NSDate date];
    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSCalendarUnitWeekday fromDate:date];
    NSInteger weekday = [componets weekday];//1代表星期日,2代表星期一,后面依次
    NSArray *weekArray = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
    NSString *weekStr = weekArray[weekday-1];
    NSMutableArray *thrArray = [NSMutableArray arrayWithArray:@[weekStr]];
    if (weekday-1 < 5) {
        [thrArray addObject:weekArray[weekday-1+1]];
        [thrArray addObject:weekArray[weekday-1+2]];
    } else if (weekday-1 == 5) {
        [thrArray addObject:weekArray[weekday-1+1]];
        [thrArray addObject:weekArray[0]];
    } else {
        [thrArray addObject:weekArray[0]];
        [thrArray addObject:weekArray[1]];
    }
    return thrArray;
}

#pragma mark - node初始化
- (UIPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 75, ml_ScreenWidth, 200)];
        _pickerView.layer.masksToBounds = YES;
        _pickerView.dataSource = self;
        _pickerView.delegate = self;
    }
    return _pickerView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSMutableArray *)weekArray {
    if (!_weekArray) {
        _weekArray = [NSMutableArray arrayWithArray:[self weekdayArray]];
    }
    return _weekArray;
}

- (NSMutableArray *)minuteArray {
    if (!_minuteArray) {
        _minuteArray = [[NSMutableArray alloc] init];
    }
    return _minuteArray;
}

- (NSMutableArray *)hArray {
    if (!_hArray) {
        _hArray = [[NSMutableArray alloc] init];
    }
    return _hArray;
}

- (NSMutableArray *)dhArray {
    if (!_dhArray) {
        _dhArray = [[NSMutableArray alloc] init];
    }
    return _dhArray;
}

- (UIView *)backView{
    if (!_backView) {
        _backView = [[UIView alloc] init];
        _backView.frame = CGRectMake(0, ml_ScreenHeight, ml_ScreenWidth, 300);
        _backView.backgroundColor = [UIColor whiteColor];
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_backView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(30, 30)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
        maskLayer.frame = _backView.bounds;
        maskLayer.path = maskPath.CGPath;
        _backView.layer.mask = maskLayer;
        
    }
    return _backView;
}

- (UIButton *)cancelButton{
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] init];
        _cancelButton.frame = CGRectMake(20, 5, 45, 45);
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize: 15];
        [_cancelButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UIButton *)sureButton {
    if (!_sureButton) {
        _sureButton = [[UIButton alloc] init];
        _sureButton.frame = CGRectMake(ml_ScreenWidth-65, 5, 45, 45);
        [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
        _sureButton.titleLabel.font = [UIFont systemFontOfSize: 15];
        [_sureButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_sureButton addTarget:self action:@selector(sureButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureButton;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.frame = CGRectMake(50, 10, ml_ScreenWidth-100, 30);
        _titleLabel.text = @"选择服务时间";
        _titleLabel.font = [UIFont systemFontOfSize:18];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UILabel *)detailTitleLabel {
    if (!_detailTitleLabel) {
        _detailTitleLabel = [[UILabel alloc] init];
        _detailTitleLabel.frame = CGRectMake(40, 50, ml_ScreenWidth-100, 20);
        _detailTitleLabel.text = @"周一至周日|全天可接单";
        _detailTitleLabel.textColor = [UIColor grayColor];
        _detailTitleLabel.font = [UIFont systemFontOfSize:13];
        _detailTitleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _detailTitleLabel;
}

@end


效果图:


F20505C5-585F-422D-9E62-42326C9331AF.png

推荐阅读更多精彩内容