代码之家  ›  专栏  ›  技术社区  ›  Rich

自定义渐变背景的UITableViewCell,另一个渐变作为高亮颜色

  •  10
  • Rich  · 技术社区  · 16 年前

    最重要的是,当行高亮显示时,我不知道如何更改为不同的渐变色。我尝试了一些方法,但我对框架不够熟悉,无法使其正常工作。将代码放在表委托或单元格内部的理想位置是什么?

    3 回复  |  直到 16 年前
        1
  •  19
  •   lobianco    13 年前

    我知道这个线程很旧,但是下面是问题的第一部分的解决方案(为单元格的选定和未选定状态添加渐变):

    -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
    {    
        [cell setBackgroundColor:[UIColor clearColor]];
    
        CAGradientLayer *grad = [CAGradientLayer layer];
        grad.frame = cell.bounds;
        grad.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
    
        [cell setBackgroundView:[[UIView alloc] init]];
        [cell.backgroundView.layer insertSublayer:grad atIndex:0];
    
        CAGradientLayer *selectedGrad = [CAGradientLayer layer];
        selectedGrad.frame = cell.bounds;
        selectedGrad.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
    
        [cell setSelectedBackgroundView:[[UIView alloc] init]];
        [cell.selectedBackgroundView.layer insertSublayer:selectedGrad atIndex:0];
    }
    
        2
  •  2
  •   Rob Lourens    16 年前

    我不确定第一个问题,但我认为您可以像设置backgroundView属性一样设置selectedBackgroundView属性。单元格之间的空白可能就是分隔符。你可以改变颜色就像

    tableView.separatorColor = [UIColor redColor];
    
        3
  •  2
  •   Kevin Lawrence    14 年前

    我的解决方案的特点:

    • 我从一个笔尖加载我的单元格,这样我就可以在IB中布局内容了。
    • 我从一个全局样式的对象中获取渐变色,因为我需要根据客户定制渐变色。
      • 我在笔尖中将单元格的选择颜色设置为灰色,这样默认颜色(蓝色)不会与我的配色方案冲突。
    • 我将渐变添加到背景视图中。如果不这样做,则选择颜色不会正确显示。UITableViewCell默认情况下没有背景视图,因此必须先创建它。

    最后一点是让这一切对我有用的秘密成分。

    我想在同一个单元格视图中添加多个子类。

    +(ActivityDetailCellView *) createWithStyle: (WMStyle *) style {  
      UIViewController *temporaryController = [[UIViewController alloc] 
           initWithNibName: @"ActivityDetailCellView"
           bundle: nil];
    
      ActivityDetailCellView *cell = (ActivityDetailCellView *) temporaryController.view;
    
      CAGradientLayer *lightGradient = [CAGradientLayer layer];
      lightGradient.frame = cell.bounds;
      lightGradient.colors = style.lightGradient;
    
      UIView *background = [[UIView alloc] initWithFrame: cell.bounds];
      [background.layer insertSublayer:lightGradient atIndex:0];  
      cell.backgroundView = background;
    
      return cell;
    }