import
import "NSDate+Extension.h"
NS_ASSUME_NONNULL_BEGIN
@interface LYXHWDatePickerView : UIView
typedef void(^cancelActioBlock)(void);
@property (nonatomic, retain) NSDate *minLimitDate;//限制最小时间(默认今天)
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
//@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (nonatomic, copy) cancelActioBlock cancelBlock;
(instancetype)initWithCompleteBlock:(void(^)(NSString *startDate, NSString *endDate))completeBlock;
(void)show;
@end
import "LYXHWDatePickerView.h"
import "UIView+Extension.h"
define kPickerSize self.datePicker.frame.size
define kPickerViewHeight 230
typedef void(^doneBlock)(NSString *starDate,NSString *endDate);
@interface LYXHWDatePickerView ()
//日期存储数组
NSMutableArray *_DatesArray;
NSMutableArray *_WeeksArray;
NSMutableArray *_hourArray;
NSMutableArray *_minuteArray;
NSMutableArray *_WeeksTempArray;
//记录位置
NSInteger datesIndex;
NSInteger hourIndex;
NSInteger minuteIndex;
//开始时间、结束时间
NSString *_startDateStr;
NSString *_endDateStr;
NSString *_todayStr;
BOOL _recordEndDate;
}
@property (weak, nonatomic) IBOutlet UIView *buttomView;
@property (weak, nonatomic) IBOutlet UILabel *showYearView;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UILabel *TipsLabel;
- (IBAction)doneAction:(UIButton *)btn;
@property (nonatomic, strong) UIPickerView *datePicker;
@property (nonatomic, retain) NSDate *scrollToDate;//滚到指定日期
@property (nonatomic, strong) doneBlock doneBlock;
@end
@implementation LYXHWDatePickerView
-
(instancetype)initWithCompleteBlock:(void(^)(NSString *startDate, NSString *endDate))completeBlock
{
self = [super init];
if (self) {
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] lastObject];[self defaultConfig]; [self setupUI]; if (completeBlock) { self.doneBlock = ^(NSString *startDate,NSString *endDate) { completeBlock(startDate,endDate); }; }
}
return self;
} -
(void)setupUI {
self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
if (!_minLimitDate) {
_minLimitDate = [NSDate date];
}
//点击背景是否影藏
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
tap.delegate = self;
[self addGestureRecognizer:tap];self.bottomConstraint.constant = -kPickerViewHeight;
self.backgroundColor = RGBACOLOR(0, 0, 0, 0);
[self layoutIfNeeded];[[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
[self.showYearView addSubview:self.datePicker];//时间选择器自动滚动到当前位置
NSDate now = [NSDate date];
[self.datePicker selectRow:[_DatesArray count]100 inComponent:0 animated:NO];
[self.datePicker selectRow:now.hour+_hourArray.count100 inComponent:1 animated:NO];
[self.datePicker selectRow:(now.minute/5)+ _minuteArray.count100 inComponent:2 animated:NO];
datesIndex = 0;
hourIndex = now.hour;
minuteIndex = now.minute/5;[self.doneBtn setTitleColor:[UIColor colorWithHexString:@"#C71444"] forState:UIControlStateNormal];
[self.cancelBtn setTitleColor:[UIColor colorWithHexString:@"#C71444"] forState:UIControlStateNormal];
}
-(void)defaultConfig {
if (!_scrollToDate) {
_scrollToDate = [NSDate date];
}
_startDateStr = @"";
_startDateStr = @"";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM月dd日"];
_todayStr = [dateFormatter stringFromDate:[NSDate date]];
//设置年月日时分数据
_DatesArray = [self setArray:_DatesArray];
// _WeeksArray = [self setArray:_WeeksArray];
// _WeeksTempArray = [self setArray:_WeeksTempArray];
_hourArray = [self setArray:_hourArray];
_minuteArray = [self setArray:_minuteArray];
_WeeksArray = [NSMutableArray arrayWithArray:@[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"]];
_WeeksTempArray = [NSMutableArray arrayWithArray:@[@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday"]];
for (int i=0; i<60; i++) {
NSString *num = [NSString stringWithFormat:@"%02d",i];
if (i<24){
[_hourArray addObject:num];
}
if ([num integerValue] % 5 == 0) {
[_minuteArray addObject:num];
}
}
for (NSInteger i=0; i<365; i++) {
NSString *currentDateStr = @"";
// if (i==0) {
// currentDateStr = @"今天";
// }else{
currentDateStr = [self getLastDate:i];
// }
[_DatesArray addObject:currentDateStr];
}
}
-
(NSString *)getLastDate:(NSInteger)day
{
NSDate * mydate = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
// 计算本地时区与 GMT 时区的时间差
NSInteger interval = [zone secondsFromGMT];NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = nil;
comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:mydate];
NSDateComponents *adcomps = [[NSDateComponents alloc] init];[adcomps setYear:0];
[adcomps setMonth:0];
[adcomps setDay:day];NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
NSCalendar *calendar2 = [NSCalendar currentCalendar];
unsigned unitFlag = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comp1 = [calendar2 components:unitFlag fromDate:newdate];
NSDateComponents *comp2 = [calendar2 components:unitFlag fromDate:[NSDate date]];NSString *dateFormat = @"yyyy年MM月dd日";
// if (comp1.year == comp2.year) {
// dateFormat = @"MM月dd日";
// }
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateFormat];
NSString *currentDateStr = [dateFormatter stringFromDate:newdate];
////////
// 得到当前时间(世界标准时间 UTC/GMT)
// NSDate *nowDate = [NSDate date];
// 设置系统时区为本地时区
// 在 GMT 时间基础上追加时间差值,得到本地时间
mydate = [mydate dateByAddingTimeInterval:interval];
NSString *nowDateString = [dateFormatter stringFromDate:mydate];
NSLog(@"%@",nowDateString);
///////////
NSString *week = [self getTheDayOfTheWeekByDateString:nowDateString];
if ([_WeeksTempArray containsObject:week] || [_WeeksArray containsObject:week]) {
NSInteger index = 0;
if ([_WeeksTempArray containsObject:week]) {
index = [_WeeksTempArray indexOfObject:week];
}else{
index = [_WeeksArray indexOfObject:week];
}
NSString *dateStr = [NSString stringWithFormat:@"%@ %@",currentDateStr,@""];
return dateStr;
}
return @"";
}
(void)addLabelWithName:(NSArray )nameArr {
for (id subView in self.showYearView.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
[subView removeFromSuperview];
}
}
for (int i=0; iCGFloat labelX = kPickerSize.width/(nameArr.count 2)+18+kPickerSize.width/nameArr.count*i;
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(labelX, self.showYearView.frame.size.height/2-15/2.0, 15, 15)];
label.text = nameArr[i];
label.textAlignment = NSTextAlignmentCenter;
label.font = [UIFont systemFontOfSize:14];
label.textColor = RGBCOLOR(102, 102, 102);
label.backgroundColor = [UIColor clearColor];
[self.showYearView addSubview:label];
}
}(NSMutableArray *)setArray:(id)mutableArray
{
if (mutableArray)
[mutableArray removeAllObjects];
else
mutableArray = [NSMutableArray array];
return mutableArray;
}
pragma mark - UIPickerViewDelegate,UIPickerViewDataSource
(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 4;
}(NSInteger)pickerView:(UIPickerView )pickerView numberOfRowsInComponent:(NSInteger)component {
if (component == 0 ) {
return 365200;
}else if (component == 1){
return 24200;
}else if (component == 2){
return 12200;
}
return 0;
}(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
return 40;
}(CGFloat)pickerView:(UIPickerView )pickerView widthForComponent:(NSInteger)component __TVOS_PROHIBITED;
{
if (component == 0) {
return 0.5SCREEN_WIDTH;
}else if (component == 1){
return 0.25SCREEN_WIDTH;
}else{
return 0.25SCREEN_WIDTH;
}
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel *customLabel = (UILabel *)view;
if (!customLabel) {
customLabel = [[UILabel alloc] init];
customLabel.textAlignment = NSTextAlignmentCenter;
[customLabel setFont:[UIFont systemFontOfSize:17]];
}
NSString *title;
// if ([_DatesArray[row] containsObject:@"星"]) {
//
// }
// _DatesArray[row] = [_DatesArray[row] stringByReplacingCharactersInRange:NSMakeRange(12, 3) withString:@""];
if (component==0) {
if (row < _DatesArray.count) {
// _DatesArray[row] = [_DatesArray[row] stringByReplacingCharactersInRange:NSMakeRange(12, 3) withString:@""];
title = _DatesArray[row];
}else{
title = _DatesArray[row % _DatesArray.count];
}
}
if (component==1) {
if (row < _hourArray.count) {
title = _hourArray[row];
}else{
title = _hourArray[row % _hourArray.count];
}
}
if (component==2) {
if (row < _minuteArray.count) {
title = _minuteArray[row];
}else{
title = _minuteArray[row % _minuteArray.count];
}
}
customLabel.text = title;
customLabel.textColor = [UIColor blackColor];
customLabel.adjustsFontSizeToFitWidth = YES;
return customLabel;
}
-
(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
datesIndex = row;
self.showYearView.text = @"";
}
if (component == 1) {
hourIndex = row;
}
if (component == 2) {
minuteIndex = row;
}NSString *dateStr = [NSString stringWithFormat:@"%@",_DatesArray[datesIndex % _DatesArray.count]];
// if ([dateStr isEqualToString:@"今天"]) {
// dateStr = _todayStr;
// }else{
// dateStr = [dateStr substringWithRange:NSMakeRange(0, dateStr.length-4)];
// }
NSString *selectDateStr = [NSString stringWithFormat:@"%@ %@:%@",dateStr,_hourArray[hourIndex % _hourArray.count],_minuteArray[minuteIndex % _minuteArray.count]];
if (!_recordEndDate) {
_startDateStr = selectDateStr;
}else{
_endDateStr = selectDateStr;
}
NSString *tempS = [self stringByReplacingsOfString:selectDateStr];
if(tempS.length < 13){
NSDate *date = [NSDate date];
tempS = [NSString stringWithFormat:@"%@-%@",@(date.year),tempS];
}
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *formatterDate = [formatter dateFromString:tempS];
self.scrollToDate = formatterDate;if ([self.scrollToDate compare:self.minLimitDate] == NSOrderedAscending) {
[self getNowDate:self.minLimitDate animated:YES];
self.scrollToDate = [NSDate date];
}
}
//滚动到指定的时间位置
(void)getNowDate:(NSDate )date animated:(BOOL)animated
{
if (!date) {
date = [NSDate date];
}
hourIndex = date.hour;
minuteIndex = date.minute;
[self.datePicker selectRow:hourIndex+_hourArray.count100 inComponent:1 animated:animated];
[self.datePicker selectRow:minuteIndex/5+ _minuteArray.count*100 inComponent:2 animated:animated];
}(NSString *)stringByReplacingsOfString:(NSString *)str
{
str = [str stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
str = [str stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
str = [str stringByReplacingOccurrencesOfString:@"日" withString:@""];
return str;
}
///根据时间(dateString)确定当天是星期几,输入的时间格式 yyyy-MM-dd ,如 2015-12-18
-(NSString *)getTheDayOfTheWeekByDateString:(NSString *)dateString{
dateString = [self stringByReplacingsOfString:dateString];
NSString *dateFormat = @"MM-dd";
if(dateString.length > 5){
dateFormat = @"yyyy-MM-dd";
}
NSDateFormatter *inputFormatter=[[NSDateFormatter alloc]init];
[inputFormatter setDateFormat:dateFormat];
NSDate *formatterDate=[inputFormatter dateFromString:dateString];
NSDateFormatter *outputFormatter=[[NSDateFormatter alloc]init];
[outputFormatter setDateFormat:@"EEEE-MMMM-d"];
NSString *outputDateStr=[outputFormatter stringFromDate:formatterDate];
NSArray *weekArray = [outputDateStr componentsSeparatedByString:@"-"];
return [weekArray objectAtIndex:0];
}
pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if( [touch.view isDescendantOfView:self.buttomView]) {
return NO;
}
return YES;
}
pragma mark - Action
-
(void)show {
[[UIApplication sharedApplication].keyWindow addSubview:self];
[UIView animateWithDuration:0.35 animations:^{
self.bottomConstraint.constant = 0;
self.backgroundColor = RGBACOLOR(0, 0, 0, 0.4);
[self layoutIfNeeded];
}];
} (void)dismiss {
[UIView animateWithDuration:0.35 animations:^{
self.bottomConstraint.constant = -kPickerViewHeight;
self.backgroundColor = RGBACOLOR(0, 0, 0, 0);
[self layoutIfNeeded];
} completion:^(BOOL finished) {
[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self removeFromSuperview];
}];
}
//点击确定
(IBAction)doneAction:(UIButton )btn {
if (NULL_STRING(_startDateStr)) {
_startDateStr = [NSString stringWithFormat:@"%@ %@:%@",_todayStr,_hourArray[hourIndex % _hourArray.count],_minuteArray[minuteIndex % _minuteArray.count]];
self.doneBlock(_startDateStr,_endDateStr);
// [self showPickerView];
}
// else if (NULL_STRING(_endDateStr)) {
// if (_recordEndDate) {
// WINDOWSTOAST(@"结束时间必须比开始时间晚5分钟")
// }else{
// [self showPickerView];
// }
// }else{
// NSInteger time = [self differencewithDate:_endDateStr withDate:_startDateStr];
// if (time < 560) {
// WINDOWSTOAST(@"结束时间必须比开始时间晚5分钟")
// }else{
self.doneBlock(_startDateStr,_endDateStr);
NSLog(@"%@------%@",_startDateStr,_endDateStr);
[self dismiss];
// }
// }
}(void)showPickerView
{
_recordEndDate = YES;
[UIView animateWithDuration:.5f animations:^{
self.bottomConstraint.constant = -kPickerViewHeight;
[self layoutIfNeeded];
} completion:^(BOOL finished) {
self.bottomConstraint.constant = 0;
[self layoutIfNeeded];
}];
self.TipsLabel.text = @"结束时间";
}
//取消
- (IBAction)cancelAction:(id)sender {
if (self.cancelBlock) {
self.cancelBlock();
}
[self dismiss];
}
pragma mark - getter / setter
- (UIPickerView *)datePicker {
if (!_datePicker) {
[self.showYearView layoutIfNeeded];
_datePicker = [[UIPickerView alloc] initWithFrame:self.showYearView.bounds];
_datePicker.showsSelectionIndicator = YES;
_datePicker.delegate = self;
_datePicker.dataSource = self;
}
return _datePicker;
}
/*********
比较两个时间差值
*******/
-
(NSInteger)differencewithDate:(NSString)dateString withDate:(NSString)anotherdateString{
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy年"];
NSString *temp = [dateFormatter stringFromDate:[NSDate date]];
if ([dateString length] < 14) {
dateString = [NSString stringWithFormat:@"%@%@",temp,dateString];
}
if ([anotherdateString length] < 14) {
anotherdateString = [NSString stringWithFormat:@"%@%@",temp,anotherdateString];
}
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: @"yyyy年MM月dd日 HH:mm"];
NSDate *date2 = [formatter dateFromString :dateString];
NSDate *date1 = [formatter dateFromString :anotherdateString];NSTimeInterval time = [date2 timeIntervalSinceDate:date1];
return time;
}
@end