您可以根据需要修改 Apple Developer Library 中的DateSectionTitles示例项目。
首先,您必须修改瞬态sectionIdentifier
属性的访问器函数以创建基于年+月+日(而不是仅年+月)的节标识符:
- (NSString *)sectionIdentifier {
// Create and cache the section identifier on demand.
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp) {
/*
Sections are organized by month and year. Create the section identifier
as a string representing the number (year * 10000 + month * 100 + day);
this way they will be correctly ordered chronologically regardless of
the actual name of the month.
*/
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:[self timeStamp]];
tmp = [NSString stringWithFormat:@"%d", [components year] * 10000 + [components month] * 100 + [components day]];
[self setPrimitiveSectionIdentifier:tmp];
}
return tmp;
}
其次,titleForHeaderInSection
必须更改委托方法,但思路相同:从节标识符中提取年、月和日,并从中创建标题标题字符串:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> theSection = [[fetchedResultsController sections] objectAtIndex:section];
NSInteger numericSection = [[theSection name] integerValue];
NSInteger year = numericSection / 10000;
NSInteger month = (numericSection / 100) % 100;
NSInteger day = numericSection % 100;
// Create header title YYYY-MM-DD (as an example):
NSString *titleString = [NSString stringWithFormat:@"%d-%d-%d", year, month, day];
return titleString;
}