profidash_98
profidash_98

Reputation: 349

UITableViewCell changes Content after scrolling

My Problem: Some of my Custom UITableViewCells contain an extra UILabel and an extra UIView for additional information. In my code i remove these extra UILabel and UIView when there are no information for this object. But every time the user scrolls through the UITableView these labels are hidden although there are additional information for these cell and shown up in another cell.

Here is my code:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

NBSnackTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell"];


NSDictionary *softdrinkDict = [_allSoftdrinksArray objectAtIndex:indexPath.row];

cell.snackNameLabel.text = [softdrinkDict valueForKey:@"name"];
cell.snackPriceLabel.text = [NSString stringWithFormat:@"%@ - %@", [softdrinkDict valueForKey:@"size"], [softdrinkDict valueForKey:@"preis"]];


    if ([softdrinkDict valueForKey:@"info"])
    {
        cell.accessoryType = UITableViewCellAccessoryDetailButton;
        cell.tintColor = [NBColor primaryTextColor];
        cell.snackInfoLabel.text = [softdrinkDict valueForKey:@"info"];
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell.snackInfoLabel removeFromSuperview];
        [cell.snackInfoView removeFromSuperview];
    }

    if ([softdrinkDict valueForKey:@"zusatzstoffe"])
    {
        cell.snackZusatzstoffLabel.text = [softdrinkDict valueForKey:@"zusatzstoffe"];
    }
    else
    {
        [cell.snackZusatzstoffLabel removeFromSuperview];
    }

[cell layoutContentWithRect:cell.bounds];

return cell;}

Upvotes: 0

Views: 36

Answers (1)

Julius
Julius

Reputation: 1013

I see a problem:

You're removing the label from the superview but not re-adding it as a subview of your cell.

Instead of calling removeFromSuperview on your labels, you could either set their text to @"" or make sure you add the label to your cell's contentView when there is data to be displayed.

Example:

if ([softdrinkDict valueForKey:@"zusatzstoffe"])
{
    if (![cell.snackZusatzstoffLabel isDescendantOfView:cell.contentView]) {
        [cell.contentView addSubview:cell.snackZusatzstoffLabel];
    }
    cell.snackZusatzstoffLabel.text = [softdrinkDict valueForKey:@"zusatzstoffe"];
}
else
{
    [cell.snackZusatzstoffLabel removeFromSuperview];
}

Upvotes: 1

Related Questions