sh_kai
sh_kai

Reputation: 29

IOS: Custom UITableViewCell - Strange Behaviour after Scrolling

i have a TableView with custom table cells. I add programmatically borders at the bottom of each cell to keep the screendesign layout. Everything is fine, when the App loads the first time. But after scrolling (and scrolling back to the top) multiple border lines are displayed all over the screen.

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

...

if([object.cellMessageArray[1] isEqualToString:@"wrapper"] || [object.cellMessageArray[1] isEqualToString:@"keynote"] || [object.cellMessageArray[1] isEqualToString:@"break"]) {
UIImageView *lineSeparator = [[UIImageView alloc] initWithFrame:CGRectMake(0, cell.bounds.size.height, 1024, 5)];
lineSeparator.image = [UIImage imageNamed:[NSString stringWithFormat:@"blind.png" ]];
lineSeparator.backgroundColor = [UIColor whiteColor];
[cell.contentView addSubview:lineSeparator];
}
else if([object.cellMessageArray[1] isEqualToString:@"standard"]) {
UIImageView *lineSeparator = [[UIImageView alloc] initWithFrame:CGRectMake(60, cell.bounds.size.height+4, 1024, 1)];
lineSeparator.image = [UIImage imageNamed:[NSString stringWithFormat:@"blind.png" ]];
lineSeparator.backgroundColor = [UIColor pxColorWithHexValue:@"eeeeee"];
[cell.contentView addSubview:lineSeparator];
}
}

Has anyone an idea?

Upvotes: 0

Views: 299

Answers (1)

bobnoble
bobnoble

Reputation: 5824

When you scroll a tableview, the cells are reused (dequeueReusableCellWithIdentifier) to optimize performance. In the code above, a lineSeparator image view is added to the cell each time the cellForRowAtIndexPath method is invoked. If the cell is used 5 times, it will have 5 image views added.

One way address this is to remove the lineSeparator image view from the cell before it is reused. This is typically done in the cell's prepareForReuse method.

In the cellForRowAtIndexPath, add a tag to the lineSeparator image view (e.g., lineSeparator.tag = 100;

In your cell's class, implement the prepareForReuse method. E.g.:

-(void)prepareForReuse{
    UIView *lineSeparatorView = [self.contentView viewWithTag:100];
    [lineSeparatorView removeFromSuperview];
}

Upvotes: 2

Related Questions