我的应用程序就像一本日志。我保留一天发生的事件的证据。基本上,我有一个实体(显示在桌面上)与“日期”属性。保存新事件时,使用[NSDate日期]存储当前日期。我如何组织tableview,这样所有的事件将按日期排序并显示出来?任何提示将不胜感激!TableView日期部分标题
0
A
回答
3
您应该使用NSFetchedResultsController
的sectionNameKeyPath
参数按日期区分结果。
你基本上设置要用作sectionNameKeyPath参数使用的属性,这将是这样的:
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@"date"
cacheName:nil];
那么你的数据源委托代码会是这个样子:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[fetchedResultsController sections] count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [fetchedResultsController sectionIndexTitles];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}
编辑:为了按日期对项目进行分组,只需要为托管对象创建一个临时属性 - 实质上是从实际日期派生的日期字符串。
这些在你的.h/.M的顶部像往常一样
@property (nonatomic, strong) NSString *sectionTitle;
@synthesize sectionTitle;
去现在你已经创建的属性,要覆盖其存取实际设置标题在请求时。
-(NSString *)sectionTitle
{
[self willAccessValueForKey:@"date"];
NSString *temp = sectionTitle;
[self didAccessValueForKey:@"date"];
if(!temp)
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d MMMM yyyy"]; // format your section titles however you want
temp = [formatter stringFromDate:date];
sectionTitle = temp;
}
return temp;
}
请注意,此代码实际上会检查sectionTitle是否已被缓存,并且只是重新使用它而不重新创建它。如果您期待或允许过去对象的日期发生变化,那么sectionTitle也需要更新,如果情况如此,您还需要为日期本身覆盖mutator,并添加一行以清除它sectionTitle(这样下一次标题被请求时,它将被重新创建)。
- (void)setDate:(NSDate *)newDate {
// If the date changes, the cached section identifier becomes invalid.
[self willChangeValueForKey:@"date"];
[self setPrimitiveTimeStamp:newDate];
[self didChangeValueForKey:@"date"];
[self setSectionTitle:nil];
}
最后,你应该只是改变了sectionNameKeyPath
您fetchedResultsController
到@"sectionTitle"
。
苹果有一个sample project你可以看看,如果你想看到类似的行动。
相关问题
- 1. Tableview部分按日期
- 2. 日期部分标题不起作用
- 3. 在tableView Cell中部分显示标题?
- 4. 从TableViewCell获取TableView部分标题,swift
- 5. TableView - 标题和部分不正确
- 6. 从tableView标题部分迅速奇怪的tableview滚动行为
- 7. C#日期部分
- 8. 在核心数据部分标题中管理日期
- 9. Tableview与部分
- 10. TableView部分
- 11. TableView部分
- 12. 斯威夫特 - 更改标题为标题部分垂直对齐的TableView中
- 13. 如何从选定的tableview单元格获取标题部分标题?
- 14. 部分中的数组问题(TableView)
- 15. 最好的(任何)方式将tableview部分标题混合到分组的tableview顶部
- 16. 删除界面生成器中的tableview部分的标题
- 17. 呈现TableView与标题,而不是中间部分或页脚
- 18. 使用自定义标题按钮修改tableview中的部分?
- 19. 调整tableview的第一个可见部分标题高度
- 20. 仅更换日期部分
- 21. 日期部分功能
- 22. DATEADD与部分日期
- 23. 用于部分日期
- 24. 需要部分日期
- 25. Java解析部分日期
- 26. 只有日期部分
- 27. Xcode - TableView - Multible部分
- 28. ASP.NET日期部署问题
- 29. TableView部分分隔线
- 30. 将日期标题从顶部移到底部
谢谢。现在我被困在每个对象的部分,而不是分组 – PonyLand
哦,对了!这是因为它使用的是包含实际小时数/分钟/秒而不是仅仅一天的整个日期对象。我将代码添加到我的答案的底部。 – Dima
解决了:)非常感谢你lolcat!希望这会对像我这样的未来新手有所帮助 – PonyLand