在每个 UITableViewCell 中显示备用视图 - iOS

Show alternate views in each UITableViewCell - iOS

我的 UITableViewCell 中有 2 个视图,我想在每个单元格中显示不同的视图(如果前一个单元格打开右视图,那么下一个单元格将打开左视图)。

我已经成功实现了,但是在滚动表格视图时,交替视图无法正常工作;下图示例:

我的代码是:

- (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*/
}

故事板截图:

我知道问题出在单元格的可重用性上,但我搜索了很多但没有成功。请提出解决方案。

谢谢!

您可以改为创建两个 table 视图单元格,并根据 indexPath,如果它的奇数或偶数加载左侧或右侧单元格。 假设你有奇怪的加载左图像视图。

这样您只需更改获取单元格的代码。其余部分保持不变。