必要に応じて、Apple Developer Library からDateSectionTitlesサンプル プロジェクトを変更できます。
最初に、transient プロパティのアクセサー関数を変更して、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;
}