代码之家  ›  专栏  ›  技术社区  ›  Ben Scheirman

UITableViewCell透明背景(包括imageView/accessoryView)

  •  10
  • Ben Scheirman  · 技术社区  · 15 年前

    当我设置UITableViewCells时 backgroundColor 对于半透明颜色,它看起来不错,但颜色不能覆盖整个单元格。

    周围地区 imageView accessoryView 他们将成为 [UIColor clearColor] ...

    alt text

    我已尝试明确设置 cell.accessoryView.backgroundColor cell.imageView.backgroundColor 与单元格的颜色相同 背景色 ,但它不起作用。它在图标周围放置一个小框,但不会扩展以填充左侧边缘。右边缘似乎不受此影响。

    :以下是原始表格单元格代码:

    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
            cell.opaque = NO;
            cell.textLabel.backgroundColor = [UIColor clearColor];
            cell.backgroundColor = [UIColor colorWithRed:.1 green:.1 blue:.1 alpha:.4];
            cell.textColor = [UIColor whiteColor];
        }
    
        cell.imageView.image = [icons objectAtIndex:indexPath.row];
        cell.textLabel.text = [items objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
        return cell;
    }
    
    2 回复  |  直到 8 年前
        1
  •  16
  •   Randika Vishman    9 年前

    Ben和我今天发现了这一点,这是小组的总结,以防抓到其他人。

    您必须设置单元格背景和 cell.textLabel.backgroundColor cellForRowAtIndexPath 被调用,而不仅仅是在 alloc/init 阶段(即如果 tableView 有一个出列缓存未命中)。

    因此,代码变为:

    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
            cell.opaque = NO;        
        }
    
        // All bgColor configuration moves here
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor colorWithRed:.1 green:.1 blue:.1 alpha:.4];
        cell.textColor = [UIColor whiteColor];
        cell.imageView.image = [icons objectAtIndex:indexPath.row];
        cell.textLabel.text = [items objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
        return cell;
    }
    
        2
  •  2
  •   Ramin    15 年前

    您是否考虑过设置单元格的背景色 contentView 以及保持单元、附件和图像视图透明?

    而且 this article 可能有助于向您展示一些备选方案。