第一次接触到日历的开发,表示需要学习的东西还有很多呢!
关于日历的开发,如果不进行相关设置的话,默认是没有农历的,需要我们进行设置。
核心Demo如下:
monthArr = [NSArray arrayWithObjects:
@"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",
@"九月", @"十月", @"冬月", @"腊月", nil];
dayArr = [NSArray arrayWithObjects:
@"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",
@"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十",
@"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十", nil];
unsigned unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date];
NSString *monthStr = [monthArr objectAtIndex:localeComp.month-1];
NSString *dayString = [dayArr objectAtIndex:localeComp.day-1];
当然如果你需要显示当前年份的农历表示需要新增如下设置:
NSArray *chineseYears = [NSArray arrayWithObjects:
@"甲子", @"乙丑", @"丙寅", @"丁卯", @"戊辰", @"己巳", @"庚午", @"辛未", @"壬申", @"癸酉",
@"甲戌", @"乙亥", @"丙子", @"丁丑", @"戊寅", @"己卯", @"庚辰", @"辛己", @"壬午", @"癸未",
@"甲申", @"乙酉", @"丙戌", @"丁亥", @"戊子", @"己丑", @"庚寅", @"辛卯", @"壬辰", @"癸巳",
@"甲午", @"乙未", @"丙申", @"丁酉", @"戊戌", @"己亥", @"庚子", @"辛丑", @"壬寅", @"癸丑",
@"甲辰", @"乙巳", @"丙午", @"丁未", @"戊申", @"己酉", @"庚戌", @"辛亥", @"壬子", @"癸丑",
@"甲寅", @"乙卯", @"丙辰", @"丁巳", @"戊午", @"己未", @"庚申", @"辛酉", @"壬戌", @"癸亥", nil];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSString *yearStr = [chineseYears objectAtIndex:localeComp.year-1];
效果图如下:
GitHub上第三方日历有两个可以试着使用一下:
个人推荐第一个,FSCalendar封装得比较完善。
mark --->关于代码放在什么位置FSCalendar中DataSource
有一个方法
Demo如下:
#pragma mark - FSCalendarDataSource
- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date
{
monthArr = [NSArray arrayWithObjects:
@"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",
@"九月", @"十月", @"冬月", @"腊月", nil];
dayArr = [NSArray arrayWithObjects:
@"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",
@"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十",
@"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十", nil];
unsigned unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date];
NSString *monthStr = [monthArr objectAtIndex:localeComp.month-1];
NSString *dayString = [dayArr objectAtIndex:localeComp.day-1];
NSString *chineseCal_str;
if ([dayString isEqualToString:@"初一"]) {
chineseCal_str = monthStr;
} else {
chineseCal_str = dayString;
}
return chineseCal_str;
}
其他诸如 JTCalendar 框架中如何设置农历显示,可在其DataSource
或者Delegate
中查看是否有 subtitleForDate
类似的设置