CAGradientLayer不适用于UITableView backgroundColor

时间:2014-08-01 23:39:13

标签: uitableview ios7 background-color cagradientlayer

我想在桌面视图后面有渐变背景色,它有透明的导航栏。

代码如下,但渐变颜色不会显示。

在简单的普通CAGradientLayer中尝试UIViewController的代码部分,它确实有用。

为什么它在UITableViewController中无效?

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;

    self.data = @[@"Xrsi", @"Liang", @"La", @"Dn", @"Piao", @"69", @"Sun", @"Mon", @"Xrsi", @"Dn", @"Lan", @"Liang", @"Piao", @"69", @"Sun", @"Mon"];

    UIColor * baseColor = [[UIColor alloc] initWithRed:0.016 green:0.729 blue:0.933 alpha:1.000];

    CGFloat hue;
    CGFloat saturation;
    CGFloat brightness;
    CGFloat alpha;

    self.cellColors = [[NSMutableArray alloc] initWithObjects:baseColor, nil];
    if ([baseColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]) {
        for (NSUInteger i = 0; i < [self.data count]; i ++) {
            brightness = brightness - 0.025;
            UIColor * newColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
            [self.cellColors addObject:newColor];
        }
    }

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    UIColor * bottomColor = [self.cellColors lastObject];
    CAGradientLayer * gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.view.frame;
    gradientLayer.colors = [NSArray arrayWithObjects:(id)baseColor.CGColor, (id)bottomColor.CGColor, nil];
    [self.view.layer insertSublayer:gradientLayer atIndex:0];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    cell.backgroundColor = self.cellColors[indexPath.row];
    cell.textLabel.text = self.data[indexPath.row];
    cell.textLabel.textColor = [UIColor whiteColor];

    return cell;
}

enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

  1. 创建一个简单的UIView,其图层是一个适当配置的渐变图层(听起来你已经知道如何做了)。

  2. 将该视图设为backgroundView

  3. 没有第3步。