2011-03-08 12 views
12

Estoy tratando de obtener una celda específica de una vista de tabla para poder cambiar su etiqueta y detener el indicador de actividad.cellForRowAtIndexPath devuelve nil

El problema que tengo es que cellForRowAtIndexPath devuelve nil.

Mi vista de tabla tiene solo 1 fila.

Código:

- (id) initWithNibName: (NSString*) nibNameOrNil bundle: (NSBundle*) nibBundleOrNil 
{ 
    self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil]; 

    if (self) 
    { 
     numberOfRows = 1; 
    } 

    return self; 
} 

- (NSInteger) tableView: (UITableView*) tableView numberOfRowsInSection: (NSInteger) section 
{ 
    return numberOfRows; 
} 

-(void) stopCellIndicator 
{ 

    LiveUserFeedCell* cell = (LiveUserFeedCell*)[self.liveFeed cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
    [cell.activityIndicator stopAnimating]; 
    cell.middleLabel.text = @"N/a"; 
} 

- (UITableViewCell*) tableView: (UITableView*) tableView cellForRowAtIndexPath: (NSIndexPath*) indexPath 
{ 
    static NSString *CellIdentifier = @"UserFeedCell"; 


    LiveUserFeedCell *cell = (LiveUserFeedCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LiveUserFeedCell" owner:self options:nil]; 
     cell = (LiveUserFeedCell *)[nib objectAtIndex:0]; 
    } 

    [cell.imgView setImage:[TUNinePatchCache imageOfSize:cell.imgView.frame.size forNinePatchNamed:@"bg_home_newsfeed_normal"]]; 


    if (shouldDisplayLoading == NO) 
    { 
     NSArray* songs = homeScreen.recentPlaybacks.songs; 
     TWSong* song = [songs objectAtIndex:index]; 
     cell.middleLabel.text = @""; 
     [cell.activityIndicator stopAnimating]; 

     UIFont *font = [UIFont fontWithName:@"Trebuchet MS" size:14];      

     NSString* kText =[NSString stringWithFormat:@"<b>%@</b> is listening to %@ by %@",song.user,song.title,song.artist]; 

     for(int i = 14; i > 0; i=i-1) 
     { 
      // Set the new font size. 
      font = [font fontWithSize:i]; 
      // You can log the size you're trying: NSLog(@"Trying size: %u", i); 

      /* This step is important: We make a constraint box 
      using only the fixed WIDTH of the UILabel. The height will 
      be checked later. */ 
      CGSize constraintSize = CGSizeMake(cell.isWatching.frame.size.width, MAXFLOAT); 

      // This step checks how tall the label would be with the desired font. 
      CGSize labelSize = [kText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

      /* Here is where you use the height requirement! 
      Set the value in the if statement to the height of your UILabel 
      If the label fits into your required height, it will break the loop 
      and use that font size. */ 
      if(labelSize.height <= cell.isWatching.frame.size.height) 
       break; 
     } 



     cell.isWatching.font = font; 
     cell.isWatching.text = [TTStyledText textFromXHTML:kText lineBreaks:YES URLs:YES]; 
     cell.isWatching.textAlignment = UITextAlignmentCenter; 

     ++index; 
     if (index == [songs count]) 
      index=0; 

    } 
    else 
    {  
     [cell.activityIndicator startAnimating]; 
    } 

    return cell; 
} 

Sin embargo, si hago algo como esto, me pongo una célula válida:

NSArray *indexPaths = [NSArray arrayWithObjects: 
         [NSIndexPath indexPathForRow:0 inSection:0], 
         nil]; 

numberOfRows = 0; 
[self.liveFeed deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft]; 


numberOfRows = 1; 
[self.liveFeed insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight]; 

LiveUserFeedCell* cell = (LiveUserFeedCell*)[self.liveFeed cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
[cell.activityIndicator stopAnimating]; 
cell.middleLabel.text = @"N/a"; 

alguna idea de cómo solucionar este problema? (Tal vez la primera celda por defecto no está en la fila 0 0 sección?) Primordial

+0

No puedo ver dónde está anulando cellForRowAtIndex. Mientras no lo hagas, no habrá células. – Krumelur

+0

Agregó más código ... eche un vistazo ahora. thx – Idan

Respuesta

-4

Al parecer, el problema era que el TableView no estaba configurado aún cuando consulté la celda.

+4

¿Qué quiere decir configurado? ¿Cómo lo configuras? – Carlo

+2

Mueva las dos palancas en la parte posterior en posición vertical. Luego presione el botón de inicio, es simple. – Jonny

-6

Probar:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 
+0

No.no funcionó – Idan

0

Intente utilizar:

[self.livFeed beginUpdates]; 
LiveUserFeedCell* cell = (LiveUserFeedCell*)[self.liveFeed cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
[cell.activityIndicator stopAnimating]; 
cell.middleLabel.text = @"N/a"; 
[self.liveFeed endUpdates]; 

Apple UITableView doc

+0

¿cómo está obteniendo cellForRowAtIndexPath en beginUpdates y endUpdates ayudando a asegurarse de que la celda no sea nula? –

1

que haya resuelto la cuestión de que me he enfrentado situación similar por lo que lo que he hecho que le muestro:

NSArray *cells = [contactsTable visibleCells]; 

    UITableViewCell *cell = nil; 
    NSIndexPath *path = [param objectAtIndex:1]; 
    for (UITableViewCell *aCell in cells) { 
     NSIndexPath *aPath = [contactsTable indexPathForCell:aCell]; 

     if ([aPath isEqual:path]) { 
      cell = aCell; 
     } 
    } 

extraño, pero funciona bien después de horas de ensayo error &.

5

Me encontré con el mismo problema, cellForRowAtIndexPath devolviendo nil, y por razones bastante tontas. En tableView:cellForRowAtIndexPath: llamé a un método que llamó al método que llama al [self.tableView cellForRowAtIndexPath:indexPath]. (Estaba reutilizando el código existente, y moviendo un poco de lógica en sentido descendente).

Como resultado, la celda aún no está disponible para que cellForRowAtIndexPath: regrese. O debe hacer todo su trabajo modificando la celda en tableView:cellForRowAtIndexPath: o, supongo, pasar el *cell.

13

Estaba teniendo cellForRowAtIndexPath devolviendo nil y la causa de esto para mí fue que lo estaba llamando en métodos donde la UITableView no debe haber sido inicializada y completa. Una vez que moví mi llamada al cellForRowAtIndexPath al -(void)viewDidAppear:(BOOL)animated, mi celda se devolvió correctamente.

+0

Gracias .. ¡Qué error de principiante ... – Markus

+1

Bueno, todos fuimos principiantes en algún momento! :-) –

26

Vale la pena mencionar que cellForRowAtIndexPath: también devolverá nil si la celda no está visible.

Esto puede ser un problema, especialmente cuando esté pasando ...

+1

¿Cómo lidiar con esto? Necesito una referencia a la celda, cuando otro VC está activo. – n00bProgrammer

+0

¿Qué quiere decir con "otro VC"? Otro VC (B) que está activo no afecta las celdas en un VC diferente (A). Esto se refiere a celdas dentro de 1 VC, y eso: No obtendrá una referencia a una celda si no está activa porque no existe. VC recicla algunos objetos de celda y los reutiliza. –

+0

¿Tiene sentido guardar una copia de la celda y usarla cuando sea necesario? –

3

que tiene condiciones muy similares con usted, pero me resolvieron este problema llamando a la función "super" en lugar de self.tableView. No sé por qué, pero al menos funciona. Quizás puedas intentarlo.

[super tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
+0

BTW, mi tabla es una tabla estática, puede diferir de su condición. – Christopher

+0

¡Funciona para mí, gracias! –

+0

Según Apple, desde iOS 11, debe evitar el uso del método tableView: cellForRowAtIndexPath: de lo contrario, se bloqueará su aplicación. –

Cuestiones relacionadas