2014-01-19 3 views
0

я опубликовал подобный вопрос раньше, пожалуйста, посмотрите на эту ссылку UITableView sections are not ordered as expected Проблема мне нужно решить следующий: У меня есть Tableview с настраиваемыми разделами. Заголовки разделов берутся из атрибута переходного процесса, определенного в подклассе NSManagegObject под названием ToDoItem. Атрибут переходного процесса называется sectionIdentifier. В моем Tableview ViewController У меня есть fetchedResultsController с два NSSortDescriptors заказать объекты:секции Order UITableView с использованием переходного атрибута

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"todoDueDate" ascending:YES]; 
    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc]initWithKey:@"todoName" ascending:YES]; 

Принимая во внимание, что переходный атрибут не может использоваться в качестве значения initWithKey на NSSortDescriptor, секции упорядочены в настоящее время в зависимости от значение атрибута для todoDueDate, а не значение sectionIdentifier, которое должно быть моим ожидаемым порядком. Я поставил ниже код как класс, так и первое определение раздела Identifier i в класс ToDoItem и второй класс tableView vieController.

-(NSString *)sectionIdentifier{ 

    [self willAccessValueForKey:@"sectionIdentifier"]; 
    NSString *tmp = [self primitiveValueForKey:@"sectionIdentifier"]; 
    [self didAccessValueForKey:@"sectionIdentifier"]; 


    if ([self.isSomeDay isEqualToString:@"noissomeday"]){//SI NO ES SOMEDAY 

    if (!tmp){ 



     //NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

     NSCalendar *calendar = [NSCalendar currentCalendar]; 
     NSInteger comps = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit); 

     NSDate *today = [NSDate date]; 
     NSDate *date = self.todoDueDate; 


     NSDateComponents *date1Components = [calendar components:comps 
                 fromDate: today]; 
     NSDateComponents *date2Components = [calendar components:comps 
                 fromDate: date]; 
     today = [calendar dateFromComponents:date1Components]; 
     date = [calendar dateFromComponents:date2Components]; 




     NSInteger daysAfterToday = [calendar components:NSDayCalendarUnit 
               fromDate:today toDate:date options:0].day; 
     // NSString *section; 
     if (daysAfterToday < 0) { 
      tmp = @"0"; 
     } else if (daysAfterToday == 0) { 
      tmp = @"1"; 
     } else if (daysAfterToday > 0 && daysAfterToday < 2) { 
      tmp = @"2"; 
     } else { 
      tmp = @"3"; 
     } 


     NSLog(@"TODAY = %@", today); 
     NSLog(@"DATE = %@", date); 
     NSLog(@"DAYS AFTER TODAY = %ld",(long)daysAfterToday); 



     [self setPrimitiveValue:tmp forKey:@"sectionIdentifier"]; 

    } 
    } 
    //no is someday 
    else if ([self.isSomeDay isEqualToString:@"issomeday"]){ 
     tmp = @"4"; 
    } 
    NSLog(@"Tmp= %@",tmp); 
    return tmp; 

} 

Это раздел заказа я хочу получить:

1. OVERDUE, sectionIdentifier = 0 
2. TODAY, sectionIdentifier = 1 
3. TOMORROW, sectionIdentifier = 2 
4. UPCOMING, sectionIdentifier = 3 
5. SOMEDAY, sectionIdentifier = 4 

ToDoItemsTableViewController.m

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    if (tableView == self.searchDisplayController.searchResultsTableView) 
    { 
     return 1; 
    } 
    else 
    { 
     return [[self.fetchedResultsController sections]count]; 
    } 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (tableView == self.searchDisplayController.searchResultsTableView) 
    { 
     return [self.searchResults count]; 
    } 
    else { 
    id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section]; 
    return [sectionInfo numberOfObjects]; 

    } 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 

    ToDoItem *toDoItem = nil; 



    if (tableView == self.searchDisplayController.searchResultsTableView) 
    { 
     if (cell==nil) { 
      cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
      cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; 

     } 
     NSLog(@"Configuring cell to show search results"); 
     toDoItem = [self.searchResults objectAtIndex:indexPath.row]; 
     cell.textLabel.text = toDoItem.todoName; 



     NSDate *fechaToDO = toDoItem.todoDueDate; 

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
     [dateFormatter setDateFormat:@"EEEE, dd MMMM YYYY"]; 
     NSString *fechaToDo = [dateFormatter stringFromDate:fechaToDO]; 

     NSString *valorSomeDay = toDoItem.isSomeDay; 
     if ([valorSomeDay isEqualToString:@"issomeday"]){ 
      cell.detailTextLabel.text = @"Someday"; 
     } 
     else { 

     cell.detailTextLabel.text = fechaToDo; 
     } 
    } 
    else 
    { 


    ToDoItem *todoitem = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    cell.textLabel.text = todoitem.todoName; 



    NSDate *fechaToDO = todoitem.todoDueDate; 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
    [dateFormatter setDateFormat:@"EEEE, dd MMMM YYYY"]; 
    NSString *fechaToDo = [dateFormatter stringFromDate:fechaToDO]; 



     NSString *valorSomeDay = todoitem.isSomeDay; 
     if ([valorSomeDay isEqualToString:@"issomeday"]){ 
      cell.detailTextLabel.text = @"Someday"; 
     } 
     else { 

      cell.detailTextLabel.text = fechaToDo; 
     } 
    } 
    return cell; 
} 

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    static NSString *header = @"customHeader"; 

    UITableViewHeaderFooterView *vHeader; 

    vHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:header]; 

    if (!vHeader) { 
     vHeader = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:header]; 
     vHeader.textLabel.backgroundColor = [UIColor redColor]; 
     vHeader.textLabel.textColor = [UIColor whiteColor]; 

     vHeader.contentView.backgroundColor = [UIColor redColor]; 
    } 

    if (section == 0) { 
     vHeader.textLabel.backgroundColor = [UIColor redColor]; 
     vHeader.textLabel.textColor = [UIColor whiteColor]; 


     vHeader.contentView.backgroundColor = [UIColor redColor]; 
    } 

    else if (section == 1) { 
     vHeader.textLabel.backgroundColor = [UIColor orangeColor]; 
     vHeader.textLabel.textColor = [UIColor blueColor]; 

     vHeader.contentView.backgroundColor = [UIColor orangeColor]; 
    } 
    else if (section == 2) { 
     vHeader.textLabel.backgroundColor = [UIColor greenColor]; 
     vHeader.textLabel.textColor = [UIColor whiteColor]; 

     vHeader.contentView.backgroundColor = [UIColor greenColor]; 
    } 
    else if (section == 3) { 
     vHeader.textLabel.backgroundColor = [UIColor greenColor]; 
     vHeader.textLabel.textColor = [UIColor whiteColor]; 

     vHeader.contentView.backgroundColor = [UIColor greenColor]; 
    } 
    else if (section == 4) { 
     vHeader.textLabel.backgroundColor = [UIColor blueColor]; 
     vHeader.textLabel.textColor = [UIColor whiteColor]; 

     vHeader.contentView.backgroundColor = [UIColor blueColor]; 
    } 


    vHeader.textLabel.text = [self tableView:tableView titleForHeaderInSection:section]; 

    return vHeader; 
} 
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 

    if (tableView == self.searchDisplayController.searchResultsTableView){ 
     NSString *valor = [NSString stringWithFormat:@"S E A R C H R E S U L T S (%d)",[self.searchResults count]]; 
     return valor; 
    } 
    else { 


    id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections]objectAtIndex:section]; 
    NSString *sectionname = [theSection name]; 

    if ([sectionname isEqualToString:@"0"]){ 

     NSString *valor = [NSString stringWithFormat:@"O V E R D U E (%d)", [self.tableView 
                  numberOfRowsInSection:section]]; 
     return valor; 
    } 
    else if ([sectionname isEqualToString:@"1"]){ 

     NSString *valor = [NSString stringWithFormat:@"T O D A Y (%d)", [self.tableView 
              numberOfRowsInSection:section]]; 
     return valor; 
    } 
    else if ([sectionname isEqualToString:@"2"]){ 

     NSString *valor = [NSString stringWithFormat:@"T O M O R R O W (%d)", [self.tableView 
                  numberOfRowsInSection:section]]; 
     return valor; 
    } 
    else if ([sectionname isEqualToString:@"3"]){ 

     NSString *valor = [NSString stringWithFormat:@"U P C O M I N G (%d)", [self.tableView 
                       numberOfRowsInSection:section]]; 
     return valor; 
    } 

    else if ([sectionname isEqualToString:@"4"]){ 

     NSString *valor = [NSString stringWithFormat:@"S O M E D A Y (%d)", [self.tableView 
                       numberOfRowsInSection:section]]; 
     return valor; 
    } 


    if ([[self.fetchedResultsController sections]count]>0){ 
     id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section]; 
     return [sectionInfo name]; 
    } 
    else{ 
     return nil; 
    } 
    } 

} 


#pragma mark - Fetched Results Controller Section 

-(NSFetchedResultsController*)fetchedResultsController{ 

    if (_fetchedResultsController != nil){ 
     return _fetchedResultsController; 
    } 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init]; 
    NSManagedObjectContext *context = self.managedObjectContext; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ToDoItem" inManagedObjectContext:context]; 
    [fetchRequest setEntity:entity]; 

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"todoDueDate" ascending:YES]; 
    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc]initWithKey:@"todoName" ascending:YES]; 

    NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor,sortDescriptor1, nil]; 
    fetchRequest.sortDescriptors = sortDescriptors; 
    _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:@"sectionIdentifier" cacheName:nil]; 
    _fetchedResultsController.delegate = self; 
    return _fetchedResultsController; 
} 
+0

Пожалуйста, удалите сброс кода из вашего вопроса. Сократите, например. код контроллера табличного представления только для соответствующих частей. – Mundi

+0

Спасибо @Mundi. Я удалил весь ненужный код. – mvasco

+0

Почему вы перепродаете это? Вы опубликовали тот же вопрос вчера, и @sebastian предоставил вам ответ – Pavan

ответ

1

Я полагаю, что "Someday" записи являются те, где todoDueDate является «неопределенным ». Проблема в том, что дескриптор сортировки «todoDueDate» должен быть совместим с идентификатором раздела. Таким образом, вы не можете использовать два отдельных свойства todoDueDate и isSomeDay для разделов.

Таким образом, вместо того, чтобы использовать отдельное свойство isSomeDay, вы должны назначить эти объекты значение, которое далеко в будущем:

self.todoDueDate = [NSDate distantFuture]; 

так, что они будут автоматически заказаны после всех других объектов. Затем вы можете сделать что-то подобное в методе sectionIdentifier:

if ([self.todoDueDate isEqualToDate:[NSDate distantFuture]) { 
    tmp = @"4"; 
} else { 
    // ... your other checks for overdue, today, tomorrow, upcoming 
} 

Также в viewForHeaderInSection, вы не должны проверить номер раздела, но для имени раздела («0», «1», .. .). Причина в том, что раздел может быть пустым: Если объектов «OVERDUE» нет, то «СЕГОДНЯ» - это раздел № 0.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section]; 

    NSString *tmp = [theSection name]; 
    if ([tmp isEqualToString:@"0"]) { 
     // OVERDUE 
    } else if ([tmp isEqualToString:@"1"]) { 
     // TODAY 
    } else 
    // and so on ... 
} 
+0

Вы имеете в виду метод titleForHeaderInSection вместо метода viewForHeaderInSection во второй части ответа? – mvasco

+0

@mvasco: Вы внедрили viewForHeaderInSection в свой код, а не titleForHeaderInSection, поэтому я выбрал это. –

+0

реализованы оба метода. – mvasco

Смежные вопросы