太长时间没有写文章了,最近几个月一直忙找工作的事情,现在终于尘埃落定,于是又从OC的坑掉进了swift的坑里,不过大家不要担心,楼主是不会丢弃掉OC的,这篇文章也是针对OC于swift区别来写的,说出来一把辛酸泪。不说了,直接进入正题吧。
这次的文章不做日历的详细介绍,因为是其本身已经封装好的,这次只是针对swift日历的具体用法做一个介绍,直接上代码。
首先先看一下效果图:
可以自动翻页,万年历,可以选中日期回传
这里写的日历主要用了NSCalendar这个API,对应的swift用的Calendar,这里的话先介绍一下官方API是怎么解释NSCalendar的:
NSCalendar objects encapsulate information about systems of reckoning time in which the beginning, length, and divisions of a year are defined. They provide information about the calendar and support for calendrical computations such as determining the range of a given calendrical unit and adding units to a given absolute time
经过一番谷歌翻译后:
NSCalendar对象封装了关于一年的开始,长度和分割定义的推算时间的信息。 它们提供有关日历的信息,并支持日历计算,例如确定给定的日历单位的范围,并将单位添加到给定的绝对时间
多的不需要太多的介绍,直接看用法吧:
首先是计算当前日期或选择的日期是几号:
//OC版本
-(NSInteger)dayWithDate:(NSDate *)date{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *component = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
return component.day;
}
//swift版本
func day(date : Date) -> NSInteger {
let calendar = Calendar.current
let componentsSet = Set<Calendar.Component>([.year, .month, .day,])
var componentss = calendar.dateComponents(componentsSet, from: date)
return componentss.day!
}
这里要注意的是,swift不能像OC直接使用NSCalendarUnit单位并且用单目运算符连接,而是需要用Set对象承载起来使用Set对象,同理这里返回的是日子,而返回月和年只需要改为month和year即可。
计算每个月1号对应周几
//OC版本
- (NSInteger)firstWeekDayInThisMonthWithDate:(NSDate *)date{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *component = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
calendar.firstWeekday = 1;
component.day = 1;
NSDate *firstDate = [calendar dateFromComponents:component];
return [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDate] - 1;
}
//swift版本
func firstWeekDayInThisMonth(date : Date) -> NSInteger {
var calendar = Calendar.current
let componentsSet = Set<Calendar.Component>([.year, .month, .day,])
var componentss = calendar.dateComponents(componentsSet, from: date)
calendar.firstWeekday = 1
componentss.day = 1
let first = calendar.date(from: componentss)
let firstWeekDay = calendar.ordinality(of: .weekday, in: .weekOfMonth, for: first!)
return firstWeekDay! - 1
}
计算当前月份天数
//OC版本
- (NSInteger)totalDaysInThisMonthWithDate:(NSDate *)date{
return [[NSCalendar currentCalendar]rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
}
//swift版本
func totalDaysInThisMonth(date : Date) -> NSInteger {
let totalDays : Range = Calendar.current.range(of: .day, in: .month, for: date)!
return totalDays.count
}
计算指定月天数
//OC版本
- (NSInteger)getDaysInMonthWithYearAndMonth:(NSInteger)year month:(NSInteger)month{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM";
//这里视具体情况而定,如果日期带有前缀0的可不要,我这里是传入了单数字日期
NSString *monthStr = @"";
if (month < 10) {
monthStr = [NSString stringWithFormat:@"0%ld",month];
}else{
monthStr = [NSString stringWithFormat:@"%ld",month];
}
NSString *dateStr = [NSString stringWithFormat:@"%ld-%@",year,monthStr];
NSDate *date = [dateFormatter dateFromString:dateStr];
//NSCalendarIdentifierGregorian公历日历的意思
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
return [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
}
//swift版本
func getDaysInMonth( year: Int, month: Int) -> Int{
let dateFor = DateFormatter.init()
dateFor.dateFormat = "yyyy-MM"
var monthStr = ""
if month < 10 {
monthStr = "0" + String(month)
}else{
monthStr = String(month)
}
let dateStr = String(year) + "-" + monthStr
let date = dateFor.date(from: dateStr)
let calenDar = Calendar.init(identifier: Calendar.Identifier.gregorian)
let totaldays : Range = calenDar.range(of: .day, in: .month, for: date!)!
return totaldays.count
}
//这里的这个id字段NSCalendarIdentifierGregorian是公历的意思,其余的可以通过官方文档查阅
上一个月
//OC版本
- (NSDate *)nextMonthWithDate:(NSDate *)date{
NSDateComponents *component = [[NSDateComponents alloc] init];
component.month = -1;
return [[NSCalendar currentCalendar]dateByAddingComponents:component toDate:date options:NSCalendarMatchStrictly];
}
//swift版本
func lastMonth(date : Date) -> Date {
var dateComponents = DateComponents.init()
dateComponents.month = -1
let newDate = Calendar.current.date(byAdding: dateComponents, to: date)
return newDate!
}
这里说一下OC的那个options的属性,swift没有用到。这里OC使用的是NSCalendarMatchStrictly这么个东西,开始查阅别人用的日历用到这个玩意儿的时候一脸懵逼不知道是什么东西,后来专门查阅了下这个属性也没有人做解释,于是只好自己去官方文档上查阅,在查阅完成后原谅我自己英语不太好,翻译为中文之后也大概没有懂什么意思,只是知其一二,现在给大家贴上,英文就是官方API原文,中文当然就是是翻译过来的意思了,具体应用可以视自己情况而定:
NSCalendarWrapComponents
Specifies that the components specified for an NSDateComponents object should be incremented and wrap around to zero/one on overflow, but should not cause higher units to be incremented.
指定为NSDateComponents对象指定的组件应该递增,并在溢出时循环为零/ 1,但不应导致更高的单位增加。
NSCalendarMatchStrictly
Specifies that the operation should travel as far forward or backward as necessary looking for a match.
指定操作应该根据需要前进或后退,寻找匹配。
NSCalendarSearchBackwards
Specifies that the operation should travel backwards to find the previous match before the given date.
指定操作向后移动以在给定日期之前找到先前的匹配。
NSCalendarMatchPreviousTimePreservingSmallerUnits
Specifies that, when there is no matching time before the end of the next instance of the next highest unit specified in the given NSDateComponents object, this method uses the previous existing value of the missing unit and preserves the lower units' values.
指定当在给定的NSDateComponents对象中指定的下一个最高单位的下一个实例的结束之前没有匹配的时间时,此方法使用缺失单元的先前存在的值,并保留较低单位的值。
NSCalendarMatchNextTimePreservingSmallerUnits
Specifies that, when there is no matching time before the end of the next instance of the next highest unit specified in the given NSDateComponents object, this method uses the next existing value of the missing unit and preserves the lower units' values.
指定当在给定的NSDateComponents对象中指定的下一个最高单位的下一个实例的结束之前没有匹配的时间时,此方法使用缺少单元的下一个现有值并保留较低单位的值。
NSCalendarMatchNextTime
Specifies that, when there is no matching time before the end of the next instance of the next highest unit specified in the given NSDateComponents object, this method uses the next existing value of the missing unit and does not preserve the lower units' values.
指定当在给定的NSDateComponents对象中指定的下一个最高单位的下一个实例的结束之前没有匹配的时间时,此方法使用缺少单元的下一个现有值,并且不保留较低单位的值。
NSCalendarMatchFirst
Specifies that, if there are two or more matching times, the operation should return the first occurrence.
指定如果有两个或更多匹配的时间,操作应该返回第一个出现的。
NSCalendarMatchLast
Specifies that, if there are two or more matching times, the operation should return the last occurrence.
指定如果有两个或更多匹配的时间,则操作应返回最后一次出现的。
好了,基本代码介绍完毕,日历主体是使用collectionView实现的,中间如果有不好的地方或者大家有改进的地方欢迎评论去留言讨论。
下面给上代码地址:
OC版本:https://github.com/Archerry/Calendar_OC
swift版本:https://github.com/Archerry/Calendar_swift