Sha Sha - 9 days ago 6
iOS Question

Show alternate views in each UITableViewCell - iOS

I've got 2 views in my

UITableViewCell
and I want to show alternate views in each cell (if previous cell has right view ON, then next cell will have left view ON).

I've implemented it successfully, but on scrolling the tableview, alternating views not working correctly; example image below:

problem image

My code is :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LiveStreamCell" forIndexPath:indexPath];

if(cell == nil)
{
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LiveStreamCell"];
}


UIView *leftView = (UIView*)[cell viewWithTag:999];
UIView *rightView = (UIView*)[cell viewWithTag:998];

UIImageView *mediaImage;
mediaImage.clipsToBounds = YES;

UILabel *artistLabel;
UILabel *titleLabel;
UILabel *statusLabel;

if (isViewOnLeft) {

isViewOnLeft = NO;

rightView.hidden = NO;
leftView.hidden = YES;

mediaImage = (UIImageView *)[cell viewWithTag:221];

CALayer *cellImageLayer = mediaImage.layer;
[cellImageLayer setCornerRadius:74];
[cellImageLayer setMasksToBounds:YES];

artistLabel = (UILabel *)[cell.contentView viewWithTag:222];
titleLabel = (UILabel *)[cell.contentView viewWithTag:223];
statusLabel = (UILabel *)[cell.contentView viewWithTag:224];


}
else {

isViewOnLeft = YES;

leftView.hidden = NO;
rightView.hidden = YES;

mediaImage = (UIImageView *)[cell viewWithTag:121];

CALayer *cellImageLayer = mediaImage.layer;
[cellImageLayer setCornerRadius:74];
[cellImageLayer setMasksToBounds:YES];

artistLabel = (UILabel *)[cell.contentView viewWithTag:122];
titleLabel = (UILabel *)[cell.contentView viewWithTag:123];
statusLabel = (UILabel *)[cell.contentView viewWithTag:124];
}

/*Here I'm setting image (come from web URLs) and labels data*/
}


Storyboard screenshot:

storyboard

I know the issue is with reusability of cells, but I searched a lot but no luck. Please suggest a solution.

Thanks!

Answer

You could instead create two table view cells, and based on the indexPath, if its odd or even load the left or right cell. Assuming you have odd ones loading the left image view.

That way you will just have to change the code fetching the cell. Rest of it remains the same.