2012-03-08 3 views
8

Я хотел бы удалить заголовки разделов из UITableView, если для этого раздела нет строк.Удалить разделы без строк из UITableView

Я использую UILocalizedIndexedCollation для моих заголовков разделов. Поэтому, когда я создаю заголовки, я не обязательно знаю, какие разделы будут иметь контент.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    //return [customerSections count]; 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return 1; 
    } 
    return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    //NSLog(@"Section: %i", section); 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return self.filteredCustomers.count; 
    } else { 
     return [[self.customerData objectAtIndex:section] count]; 
    } 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    // The header for the section is the region name -- get this from the region at the section index. 

    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return nil;//@"Results"; 
    } 
    return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section]; 
} 

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 
{ 
    //return [customerSections allKeys]; 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return nil; 
    } 
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]; 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index 
{ 
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index]; 
} 

ответ

1

Я закончил удаление неиспользуемых разделовIndexTitles и создание разделов на основе этого.

В моем NSURLConnection requestDidFinish я использовал следующее.

self.customerData = [self partitionObjects:[self customers] collationStringSelector:@selector(self)]; 

затем был

-(NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector 
{ 
    sectionIndexTitles = [NSMutableArray arrayWithArray:[[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]]; 
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation]; 
    NSInteger sectionCount = [[collation sectionTitles] count]; 
    NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount]; 

    for (int i = 0; i < sectionCount; i++) { 
     [unsortedSections addObject:[NSMutableArray array]]; 
    } 

    for (id object in array) { 
     NSInteger index = [collation sectionForObject:[object objectForKey:@"name"] collationStringSelector:selector]; 
     [[unsortedSections objectAtIndex:index] addObject:object]; 
    } 

    NSMutableArray *sections = [NSMutableArray array]; 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]; 
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 

    NSUInteger lastIndex = 0; 
    NSMutableIndexSet *sectionsToRemove = [NSMutableIndexSet indexSet]; 
    for (NSArray *section in unsortedSections) { 
     if ([section count] == 0) { 
      NSRange range = NSMakeRange(lastIndex, [unsortedSections count] - lastIndex); 
      [sectionsToRemove addIndex:[unsortedSections indexOfObject:section inRange:range]]; 
      lastIndex = [sectionsToRemove lastIndex] + 1; 

     } else { 
      NSArray *sortedArray = [section sortedArrayUsingDescriptors:sortDescriptors]; 
      [sections addObject:sortedArray]; 
     } 
    } 

    [sectionIndexTitles removeObjectsAtIndexes:sectionsToRemove]; 

    return sections; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 

    if (self.searchDisplayController.active) { 
     return 1; 
    } 
    return [sectionIndexTitles count];//[[[UILocalizedIndexedCollation currentCollation] sectionTitles] count]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    if (self.searchDisplayController.active) { 
     return self.filteredCustomers.count; 
    } else { 
     return [[self.customerData objectAtIndex:section] count]; 
    } 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 

    if (self.searchDisplayController.active) { 
     return nil; 
    } 

    return [sectionIndexTitles objectAtIndex:section]; 
} 

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 
{ 

    if (self.searchDisplayController.active) { 
     return nil; 
    } 

    return sectionIndexTitles; 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index 
{ 
    return index;//[[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index]; 
} 

И со всеми выше код этого удалены неиспользуемые буквы с правой стороны экрана, а также заголовки разделов, которые не имели ни одной строки.

2

Это интересный вопрос с рядом возможных решений.

Рабочие обратные, numberOfSectionsinTableView и numberOfRowsInSection - это то, что необходимо обновить, чтобы отобразить правильное количество разделов. Они частично зависят от методов UILocalizedIndexedCollation.

(Предположительно это происходит после какого-либо действия пользователя (удаление или вставка), поэтому обратите внимание, что в commitEditingStyle вы должны позвонить [self.tableView reloadData).

Я предполагаю, что customerData - это массив, где в каждом индексе есть изменяемый массив, соответствующий разделу. Когда массив в определенном индексе customerData не имеет данных, вы хотите удалить раздел для этого индекса.

Решение заключается в том, чтобы вычислить все вручную - определить информацию раздела, основанную на жизнях внутри вашего массива customerData. Я принял удар, переписывая три из ваших методов. Удачи!

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 
{ 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return nil; 
    } 
    NSMutableArray *arrayToFilter = [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]; 

    //This is the key - recalculate index titles based on what's present in customerData 
    for (int i = [self.customerData count] -1; i >=0 ; i--) { 
     if (![[self.customerData objectAtIndex:i] count]) { 
      [self.arrayToFilter removeObjectAtIndex:i]; 
     } 
    } 
    return arrayToFilter; 
} 

//You need to be calculating your table properties based on the number of objects 
//rather of the 'alphabet' being used. 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    //return [customerSections count]; 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return 1; 
    } 
    //return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count]; 
    int populatedArrayCounter = 0;   
    for (int i = 0; i <[self.customerData count]; i++) { 
     if ([[self.customerData objectAtIndex:i] count]) { 
      populatedArrayCounter++; 
     } 
    } 
    return populatedArrayCounter; 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    //NSLog(@"Section: %i", section); 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return self.filteredCustomers.count; 
    } else { 
     // Your original line requires changing, because there are customerData array objects with a count of 0, and you don't want any sections like that 
     // Thus, pick from the set of populated arrays. 
     NSMutableArray populatedArrays = [[NSMutableArray alloc] init];   
     for (int i = 0; i <[self.customerData count]; i++) { 
      if ([[self.customerData objectAtIndex:i] count]) { 
       [populatedArrays addObject:i]; 
      } 
     } 
     return [[populatedArrays objectAtIndex:section] count];; 
    } 
} 
3

Я недавно достиг этого с этим кодом:

Это функция, которая возвращает название для раздела, если нет строк в этом разделе, то не возвращает название:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    if ([self.customerData count] > 0) { 
      return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section]; 
     } 
    return nil; 
} 
10

Просто хотел звенеть и дать свое решение этой

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    if ([self.myTableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) { 
     return nil; 
    } 
    return [[self.collation sectionTitles] objectAtIndex:section]; 

} 

based on this answer

+1

Хотя я в конечном итоге удаление sectionIndexTitles, а это отвечает на вопрос лучше, чем выше ответ. – Bot

0

Я хотел бы поделиться своим решением в быстрой

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    if self.sections[section].isEmpty 
    { 
     return nil 
    } 
    else 
    { 
     return collation.sectionTitles[section] 
    } 
} 
Смежные вопросы