Search code examples
iosobjective-cxcodeuitableviewuitableviewrowaction

UiTableviewCell with dynamic data init not loading correctly


in my cell data is loading but its is all messed up until i scroll down then if i scroll back everything format correctly. so when every i load listing which is uitableview data is messed up and as soon i start scrolling and scroll back up it gets in place and show correctly. please help.

my code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    for(UIView *v in [cell subviews])
    {
        if([v isKindOfClass:[UILabel class]])
            [v removeFromSuperview];
        if ([v isKindOfClass:[UIImageView class]])
            [v removeFromSuperview];
    }
UIView *CellBGView = [[UIView alloc] initWithFrame:CGRectMake(10, 5, cell.frame.size.width-20, cell.frame.size.height-10)];
    CellBGView.backgroundColor = [UIColor whiteColor];

    UIImageView *divider = [[UIImageView alloc] initWithFrame:CGRectMake(CellBGView.frame.size.width-155,       CellBGView.frame.size.height-140, 150, 150)];
    divider.image = [UIImage imageNamed:@"icon_alpha.png"];
    [CellBGView addSubview:divider];
    ......
    return cell;
}

Here is out put when i open listing and before scrolling table

enter image description here

here is after scrolling everything gets in place

enter image description here


Solution

  • I have a solution for you.

    • First, create subclass of UITableViewCell (For example, name it DemoTableViewCell)

    • In initWithStyle method of DemoTableViewCell, add your images and labels to cell.

    • In cellForRowAtIndexPath, you don't need add or remove images and labels. Just change color or set image for them.