0

I'd like to have gradient background color behind of a table view, which has transparent navigation bar.

Codes as following, but gradient color doesn't show up.

Tried code part of CAGradientLayer in a simple normal UIViewController, it does work.

Why it doesn't work in 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

4

1 回答 1

0
  1. 创建一个普通的 UIView,它的层是一个渐变层,适当的配置(听起来你已经知道怎么做)。

  2. 使该视图成为表格视图的backgroundView.

  3. 没有第 3 步。

于 2014-08-01T23:53:46.503 回答