Bindi Bindi - 5 months ago 24
Objective-C Question

UIView is overlapping / creating again in cellForRowAtIndexPath

I have

UITableViewCell
that contains
UIView
(lets call it
CPView
) which is created while
cellForRowAtIndexPath
is called.
CPView
is just a plain coloured view and for every cell its width is different (that's why needed to create in
cellForRowAtIndexPath
).

Problem is

1)The
CPView
's colour gets darker every time cell loads (May be due to every time that cell creates the same view so overlapping effect).

2) The cell overlaps / inherits other cell's
CPView
(we can see this because of light and dark colour of two
CPView
).

How can I prevent cell to recreate if it already exist or creation of this
CPView
again?

Edit

- (void)configureCell:(CreditDebitCell *)cell atIndexPath:(NSIndexPath *)indexPath {

//other code

UIView * CPView;

if (CPView){

CPView =nil;
}
else
{

CPView = [[UIView alloc] initWithFrame:CGRectMake(cell.bounds.origin.x, cell.bounds.origin.y, cell.frame.size.width*[self.percentArray[indexPath.row] floatValue] ,cell.frame.size.height )];
[CPView setClipsToBounds:YES];
[CPView setBackgroundColor:[UIColor colorWithRed:107/255.0 green:15/255.0 blue:47/255.0 alpha:0.5]];

[cell addSubview: CPView];

}

}

Answer

The issue here is reuse of the cells - and therefore you get multiple views added to your cell view.

You can:

-remove subview -check if subview exists and do/don't do anything.

You can check if the subview is there by going through subviews:

for (UIView *v in cell.contentView.subview) {
    if ([v isKindOfClass:[CPView class]]) {
        // remove or flag that it exists
    }
}

But I think that you should handle this in your cell - not your view controller that implements table view delegate. Better tell cell to use some view/hide some view based on some kind of logic then to do that inside cellForRowAtIndexPath

Comments