James
James

Reputation: 6499

Adding border subview to UITableViewCell dynamically

I'm trying to add a custom bottom border to all of my tableview cells using a UIImageView that I add to the cell programmatically at runtime. The problem is that often as the user scrolls, the border will disappear randomly.

This code is in my cellForRowAtIndexPath method:

UIImageView* border = (UIImageView*)[cell viewWithTag:10];
if (border)
    [border removeFromSuperview];

NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
NSInteger row = indexPath.row;

if (row != sectionRows - 1) {
    UIImageView* border = [[UIImageView alloc] initWithImage:[[ImageManager sharedManager] imageNamed:@"dashed_border"]];
    [border setFrame:CGRectMake(10, [self tableView:tableView heightForRowAtIndexPath:indexPath], 290, 1)];
    [border setTag:10];
    [cell addSubview:border];
    [border release];
}

It removes a border subview if it exists, and if the row is not a bottom row, it inserts the border at the bottom of the row.

I'm not sure if this is a race condition, or if there are certain times in which cellForRowAtIndexPath isn't called as the user scrolls.

Upvotes: 0

Views: 579

Answers (1)

murat
murat

Reputation: 4963

Probably the cell below is drawn on top of the border. It depends on the order of the subviews in the table view and the order changes as you scroll.

This happens because you are adding the border outside of the cell bounds. Try moving it 1px up. Like:

[border setFrame:CGRectMake(10, [self tableView:tableView heightForRowAtIndexPath:indexPath] - 1, 290, 1)];

Upvotes: 1

Related Questions