日期选择器(仿比心)

话不多说,贴上代码

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

推荐阅读更多精彩内容