2012-03-08 20 views
8

Quisiera quitar encabezados de sección de una UITableView si no hay filas para esa sección.Eliminar secciones sin filas de UITableView

Estoy usando UILocalizedIndexedCollation para mis encabezados de sección. Entonces, cuando creo los encabezados, no necesariamente sé qué secciones tendrán contenido.

- (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]; 
} 

Respuesta

1

Terminé eliminando el sectionIndexTitles no utilizado y creando las secciones basadas en eso.

En mi NSURLConnection requestDidFinish usé lo siguiente.

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

entonces tenían

-(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]; 
} 

Y con todo el código por encima de este retiran las cartas no utilizados del lado derecho de la pantalla, así como los encabezados de sección que no tenían filas.

2

Es una pregunta interesante, con una serie de posibles soluciones.

Trabajando al revés, numberOfSectionsinTableView y numberOfRowsInSection son lo que debe actualizarse para mostrar el número correcto de secciones. Estos son parcialmente dependientes de los métodos UILocalizedIndexedCollation métodos.

(Presumiblemente, esto sucede después de algún tipo de acción del usuario (una eliminación o una inserción), así que tenga en cuenta que en commitEditingStyle debe llamar al [self.tableView reloadData).

Supongo que customerData es una matriz, donde en cada índice hay una matriz mutable que corresponde a una sección. Cuando la matriz en un determinado índice customerData no tiene datos, desea eliminar la sección de ese índice.

La solución entonces es calcular todo manualmente: determine la información de la sección en función de las vidas dentro de su matriz customerData. Intenté reescribir tres de tus métodos. ¡Buena suerte!

- (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

que he logrado recientemente esta con este código:

Ésta es la función que devuelve el título de la sección, si no hay filas en esa sección y luego no regresan un título:

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

Sólo quería meter su cuchara y dar mi solución a este

- (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

A pesar de que terminó la eliminación de los sectionIndexTitles, así que esto responde a la pregunta mejor que la respuesta anterior. – Bot

0

que quería compartir mi solución rápida en

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    if self.sections[section].isEmpty 
    { 
     return nil 
    } 
    else 
    { 
     return collation.sectionTitles[section] 
    } 
} 
Cuestiones relacionadas