2010-07-20 15 views
8

Mi UITableView obtiene datos de Internet. Algunas veces no recibe ningún dato (celular). Simplemente muestra una tabla en blanco.UITableView Pantalla sin datos

¿Cómo puedo mostrar un mensaje/celda al usuario de que no se han encontrado registros de datos?

Respuesta

25

Desea devolver una celda informando sobre la falta de datos.

Si es mantener los datos de la celda en una matriz que es una propiedad de clase (digamos NSArray *listings), puede ir:

-(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section 
{ 
    if ([self.listings count] == 0) { 
     return 1; // a single cell to report no data 
    } 
    return [self.listings count]; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if ([self.listings count] == 0) { 
     UITableViewCell *cell = [[[UITableViewCell alloc] init] autorelease]; 
     cell.textLabel.text = @"No records to display"; 
     //whatever else to configure your one cell you're going to return 
     return cell; 
    } 

    // go on about your business, you have listings to display 
} 
+0

es una buena idea para almacenar en caché esta célula como con otras células normales? si es así, ¿cómo haces eso? – Yazzmi

+0

No tiene que preocuparse por el almacenamiento en caché de esta celda porque se va a desaparecer en el momento en que tenga datos reales para mostrar, y la liberación automática se encargará de su memoria. Nunca se moverá de la mesa, por lo que no hay nada que guardar en la memoria caché. Por cierto, usted debe hacer esto, ya que CARGUE sus datos también. Luego, cuando su proceso de red finalice y haya completado su fuente de datos, llame a 'reloadData' en su UITableView. –

+0

funciona como un amuleto: solo tuve que ajustar la fuente un poco para obtener el mensaje que quería encajar: [cell.textLabel setFont: [UIFont fontWithName: @ Helvetica-Bold "size: 13]]; – jaySF

2

Puede agregar una prueba en su -tableView: cellForRowAtIndexPath: implementación y mostrar una UITableViewCell especial que dice "no hay resultados disponibles" cuando no obtiene datos.

Otro enfoque, que por lo general se ve mejor, es agregar una vista personalizada al UITableView directamente. No olvides quitarlo cuando haya resultados para mostrar.

2

se puede añadir un UILabel a la vista Esto puede ser creado mediante programación o en tu xib. Si su xib contiene una UITableView como [Ver auto], como es típico para un UITableViewController, a continuación, crear una propiedad de la etiqueta de su viewController

@property (nonatomic, retain) IBOutlet UILabel  *noResultsLabel; 

Arrastre un UILabel de la biblioteca en la ventana de documento como un hermano a su "Vista de tabla". Establecer propiedades de texto (fuente en negrita de 36 pt, gris claro se ve bastante bien)
Control de arrastre desde "Propietario del archivo" para conectar la salida a la etiqueta.

UITableView with no results UILabel

En su devolución de llamada del servidor, puede agregar la etiqueta a la vista. He aquí un ejemplo:

#pragma mark - 
#pragma mark Server callbacks 
- (void)serviceExecutionComplete:(NSMutableArray *)results { 
    [self setServerData:results]; 
    if ([results count] == 0) 
    { 
     // no results, 
     CGRect viewFrame = [[self view] frame]; 
     [[self noResultsLabel] setFrame:CGRectMake(0, (viewFrame.size.height - 100)/2, viewFrame.size.width, 50.0)]; 
     [[self view] addSubview:[self noResultsLabel]]; 
    } 
    else 
    { 
      [[self noResultsLabel] removeFromSuperview]; 
     [self.tableView reloadData]; 
    } 
} 

Usted podría hacer lo mismo en tableView: numberOfRowsInSection: si eso se adapte a su mejor diseño

1

yo estaba contemplando mostrando una emptyDataView en cualquiera de encabezado/pie de página, o la piratería uno de la fila como la respuesta sugerida de Dan.

Pero creo que lo más limpio es crear una vista fuera de tableView.

@property (weak, nonatomic) IBOutlet UIView *emptyDataView; 

Entonces Ocultar/mostrar la vista en numberOfRowsInSection: así:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    id sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section]; 

    // Show empty data view if no data 
    _emptyDataView.hidden = ([sectionInfo numberOfObjects] == 0) ? NO : YES; 

    return [sectionInfo numberOfObjects]; 
} 

Esto funciona bien con la base de datos NSFetchedResultsController y ocultar la vista una vez que hay datos.

1

Como se menciona en el enlace a continuación, es fácil si creamos una etiqueta y la configuramos como vista de fondo para UITableView, como se muestra a continuación. Puede ser que sea útil para alguien. http://www.appcoda.com/pull-to-refresh-uitableview-empty/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    if (data) { 
     self.tableView.backgroundView = nil; 
     self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 
     return 1; 

    } else { 

     // Display a message when the table is empty 
     UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)]; 

     messageLabel.text = @"No data is currently available. Please pull down to refresh."; 
     messageLabel.textColor = [UIColor blackColor]; 
     messageLabel.numberOfLines = 0; 
     messageLabel.textAlignment = NSTextAlignmentCenter; 
     messageLabel.font = [UIFont fontWithName:@"Palatino-Italic" size:20]; 
     [messageLabel sizeToFit]; 

     self.tableView.backgroundView = messageLabel; 
     self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; 

    } 

    return 0; 
} 
+0

Intenté este enfoque. Tenga en cuenta que si devuelve 0 secciones cuando no tiene datos, la aplicación se bloquea si usa deleteRowsAtIndexPaths. Para remediar esto, siempre devuelvo 1 por el número de secciones. También agregué 'self.tableView.backgroundView = nil' si existen datos. – davew

-1

Aquí, he utilizado un código como:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
NSInteger numOfSections = 0; 
if ([jsonArray count] != 0){ 
    tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 
    numOfSections     = 1; 
    tableview.backgroundView = nil; 
} 
else{ 
    UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableview.bounds.size.width, tableview.bounds.size.height)]; 
    noDataLabel.text    = @"No item found."; 
    noDataLabel.textColor  = [UIColor blackColor]; 
    noDataLabel.textAlignment = NSTextAlignmentCenter; 
    tableview.backgroundView  = noDataLabel; 
    tableview.separatorStyle  = UITableViewCellSeparatorStyleNone; 
} 
    return numOfSections; 
} 

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section{ 
    return [jsonArray count ]; 
} 
Cuestiones relacionadas