自定义部分标题的 sectionIdentifier 仅按月或年分组

Posted

技术标签:

【中文标题】自定义部分标题的 sectionIdentifier 仅按月或年分组【英文标题】:sectionIdentifier for Custom Section Titles group by month or year only 【发布时间】:2015-07-28 23:02:36 【问题描述】:

我想知道是否有人可以帮助我。我试图仅按月或年而不是按天对日期记录进行分组。我感谢您的帮助。

`(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section

 id theSection = [[self.fetchedResultsController sections] objectAtIndex:section];

/* 节信息来自事件的节标识符,它是一个字符串,表示数字(年 * 1000)+ 月。要显示部分标题,请将年份和月份组件转换为字符串表示形式。 */

     static NSDateFormatter *formatter = nil;

     if (!formatter)  formatter = [[NSDateFormatter alloc] init];  [formatter setCalendar:[NSCalendar currentCalendar]];

    NSString *formatTemplate = [NSDateFormatter dateFormatFromTemplate:@"MMM YYYY" options:0 locale:[NSLocale currentLocale]];
    [formatter setDateFormat:formatTemplate];
    

     NSInteger numericSection = [[theSection name] integerValue];
    NSInteger year = numericSection / 10000;
    NSInteger month = (numericSection - (year * 10000))/100;
   NSInteger day = (numericSection - (year * 10000 + month * 100));


    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.year = year;
    dateComponents.month = month;
    dateComponents.day = day;
    NSDate *date = [[NSCalendar currentCalendar]           dateFromComponents:dateComponents];

    NSString *titleString = [formatter stringFromDate:date];

    return titleString;
    `

【问题讨论】:

【参考方案1】:

您需要在 NSManagedObject 子类中将自定义部分标题作为属性实现(在类别中,如果您自动生成 NSManagedObject 类)。这个 *** answer 就是你要找的。​​p>

【讨论】:

感谢安东尼斯的回复。我尝试了你的建议,但它对我不起作用。我正在使用 NSFetchedResultsController 来管理我的核心数据记录。使用上面的 NSInteger 日期计算可以很好地按天对记录进行分组,但我想分别按月和年对它们进行分组。再次感谢

以上是关于自定义部分标题的 sectionIdentifier 仅按月或年分组的主要内容,如果未能解决你的问题,请参考以下文章

NSFetchedResultsController 每 4 小时分组一次

自定义 UITableView 部分标题 alpha 0

自定义 UITableViewController 的标题部分

可折叠部分和每个部分的多个自定义 UITableViewCell

自定义 UITableView 部分标题视图正在破坏

带有自定义 UICollectionViewLayout 的 UICollectionView 中的部分标题