本文主要是介绍iOS仿酒店入住离店日历(Calendar)选择,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近做一个项目,有个日历选择功能,就仿美团做了一个,将思路、代码分享一下。先上图片,直观体验一下
Demo下载地址:
https://github.com/TechAlleyBoy/CalendarDemo
http://download.csdn.net/download/techalleyboy/9840841
一:数据源的准备工作,各种日期的计算工作
1:根据NSDate获得年月日,及星期几
#pragma mark - 获取年,月,日,星期
//注:日历获取在9.x之后的系统使用currentCalendar会出异常。在8.0之后使用系统新API。
-(NSInteger )getDataFromDate:(NSDate *)date type:(NSString * )type{NSCalendar *calendar = nil;if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];}else{calendar = [NSCalendar currentCalendar];}NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitWeekday) fromDate:date];if ([type isEqualToString:@"year"]) {return components.year;}else if ([type isEqualToString:@"month"]) {return components.month;}else if ([type isEqualToString:@"day"]) {return components.day;}else if ([type isEqualToString:@"week"]) {return components.weekday;}else{return 0;}
}
2:根据NSDate获得当月一共几天
#pragma mark -- 获取当前月共有多少天
- (NSInteger)totaldaysInMonth:(NSDate *)date{NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];return daysInLastMonth.length;
}
3:时间字符串转时间
#pragma mark - 时间字符串转时间
-(NSDate *)dateWithYear:(NSInteger )year month:(NSInteger )month day:(NSInteger )day
{NSDateFormatter *formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"yyyyMMdd"];
return [formatter dateFromString:[NSString stringWithFormat:@"%ld%02ld%02ld",year,month,day]];
}
二:模型Model的建立
注:模型里面套模型 月的模型(MonthModel) 中 有一个NSArray
//
// MonthModel.h
// BJTResearch
//
// Created by yunlong on 17/5/12.
// Copyright © 2017年 yunlong. All rights reserved.
//#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>typedef enum : NSUInteger {DayModelStateNormal = 0,DayModelStateStart,DayModelStateEnd,DayModelStateSelected,
} DayModelState;typedef enum : NSUInteger {Sunday = 1,Monday,Tuesday,Wednesday,Thursday,Friday,Sat
这篇关于iOS仿酒店入住离店日历(Calendar)选择的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!