Search code examples
iosuitabview

Custom cell contents overlapping in UITableView


I know this question is already asked many times, but my problem is some different.

I am creating a UIView and a UIImageView programmatically in cell's content view. When TableView appear first time it looking perfect, but when i scroll down and up , this seems overlapped.

Screenshot of without scroll:

enter image description here

Screenshot after scroll:

enter image description here

Code that i follow:

 viewForHead = [[UIView alloc]initWithFrame:CGRectMake(cell.viewForContents.frame.origin.x, cell.viewForContents.frame.origin.y-10, cell.viewForContents.frame.size.width, 45)];
viewForHead.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:255.0/255.0 blue:16.0/255.0 alpha:1];
[cell.contentView addSubview:viewForHead];

UIImageView *imageViewForDP = [[UIImageView alloc]initWithFrame:CGRectMake(viewForHead.frame.origin.x-50, viewForHead.frame.origin.y-8, 60,60 )];
imageViewForDP.image = [UIImage imageNamed:@"dog_1.png"];
//[cell.viewForContents addSubview:imageViewForDP];
imageViewForDP.layer.cornerRadius = 30;
imageViewForDP.clipsToBounds = YES;
[viewForHead addSubview:imageViewForDP];

Please get me out from this problem . Thanks


Solution

  • Use this into your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    if ([cell.contentView subviews]){
        for (UIView *subview in [cell.contentView subviews]) {
            [subview removeFromSuperview];
        }
    }