Вам необходимо определить приращения даты для вашего вида таблицы, то есть каждый раздел будет представлять элементы в пределах одной секунды, часа, дня e.t.c.
Предположим, что вы решили на день вы могли бы идти об этом так:
// We will need a date formatter for later
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
// 1) Get the oldest and newest items
NSDate *oldest = [(Item *)items.firstObject eventDate];
NSDate *newest = [(Item *)items.lastObject eventDate];
// 2) Get an array with the relevant dates in it...
NSTimeInterval timeDiffSecs = [newest timeIntervalSinceDate:oldest];
int days = (((timeDiffSecs/60)/60)/24) + 1;
NSMutableArray *dates = [[NSMutableArray alloc] init];
for (int i = 0; i < days; i++) {
[dates addObject:[NSDate dateWithTimeInterval:((24 * 60) *60) * i since date:oldest]];
}
Затем, используя эти данные вам необходимо реализовать следующие методы источника UITableView
данных:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// This is the date that you will group the items under
NSDate *sectionDate = dates[indexPath.section];
NSArray *filteredItems = [items filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"eventDate >= %@ AND eventDate < %@", sectionDate, sectionDate]];
Item *item = filteredItems[indexPath.row];
// Then fill out the cell using the item.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the amount of rows for each given section...
NSDate *sectionDate = dates[indexPath.section];
return [[items filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"eventDate >= %@ AND eventDate < %@", sectionDate, sectionDate]] count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// This is easy this is just the number of dates we originally found...
return dates.count;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
// This is asking for the section with applies to the given title
// 1) Get the date from the string
NSDate *date = [formatter dateFromString:title];
NSArray *filtered = [dates filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF >= %@ AND SELF < %@", date, date]];
// The above array should only contain 1 date
return [dates indexOfObject:filtered[0]];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
// This is asking for the title for the given section
NSDate *date = dates[section];
return [formatter stringFromDate:date];
}
Примечание: эти данные исходные методы - это то, что вам нужно реализовать для организации объектов в представлении таблицы по определенному атрибуту, например Дата. Тем не менее, код, который я использовал для фильтрации дат e.t.c, является только примером, и я его не тестировал, поэтому может потребоваться некоторая настройка.
Возможный дубликат [Сортировка разделов таблицы по NSDate] (http://stackoverflow.com/questions/28793654/sorting-table-sections-by-nsdate) – Larme
@ У вас есть ответ? – Mrunal
@Mrunal Нет, я не получил ответ, который мне нужен, однако я решил, что я опережаю себя, пытаясь реализовать вещи, которые я не понимаю, поэтому я вернусь к документации и учебникам. Даже с примером кода в ответах ниже я не мог заставить его работать, поэтому пришло время вернуться к чертежной доске. Спасибо всем за вход, не уверен, что за голоса были, поскольку я думал, что это был разумный вопрос, но тогда это, вероятно, больше, я еще не понимаю! – AB567