如何在ios中重新加载时在动态表格单元格中应用渐变颜色层

时间:2016-06-20 10:49:18

标签: ios objective-c swift uitableview

我想创建渐变类型的颜色代码并设置为动态表格视图单元格,其高度根据数据而变化。 当我要添加到表格单元格层时,我使用了图层。表数据加载后我需要精确的表格视图单元格高度。

-(void)setTableData:(NSMutableArray *)tableData{

    tableHeightConstraints.constant  = cellHeight * tableData.count;

    _tableData = tableData;

    [self.tableView reloadData];

    [self layoutIfNeeded];

    CAGradientLayer *bgLayer = [self greyGradient];
    bgLayer.cornerRadius = 5.0f;
    bgLayer.frame = CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height);
    self.backgroundImageViewTc.image = [self greyImageFromGradient:bgLayer];

    [self layoutIfNeeded];
}


+ (CAGradientLayer*) greyGradient {

    UIColor *colorOne = [UIColor colorWithWhite:0.9 alpha:1.0];
    UIColor *colorTwo = [UIColor colorWithHue:0.625 saturation:0.0 brightness:0.85 alpha:1.0];
    UIColor *colorThree     = [UIColor colorWithHue:0.625 saturation:0.0 brightness:0.7 alpha:1.0];
    UIColor *colorFour = [UIColor colorWithHue:0.625 saturation:0.0 brightness:0.4 alpha:1.0];

    NSArray *colors =  [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, colorThree.CGColor, colorFour.CGColor, nil];

    NSNumber *stopOne = [NSNumber numberWithFloat:0.0];
    NSNumber *stopTwo = [NSNumber numberWithFloat:0.02];
    NSNumber *stopThree     = [NSNumber numberWithFloat:0.99];
    NSNumber *stopFour = [NSNumber numberWithFloat:1.0];

    NSArray *locations = [NSArray arrayWithObjects: stopOne, stopTwo, stopThree, stopFour, nil];
    CAGradientLayer *headerLayer = [CAGradientLayer layer];
    headerLayer.colors = colors;
    headerLayer.locations = locations;

    return headerLayer;

}

+ (UIImage *) greyImageFromGradient:(CAGradientLayer*) layer{

    UIGraphicsBeginImageContext(layer.bounds.size);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

此代码无法创建精确尺寸的图像,因此模糊不清。

2 个答案:

答案 0 :(得分:3)

  

在这里你可以找到你的解决方案让我知道是否有任何问题

- (void)tableView:(UITableView )tableView willDisplayCell:(UITableViewCell )cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    TVCell mycell = (TVCell )cell;

    CGSize size = CGSizeMake(mycell.cellBkView.frame.size.width, mycell.cellBkView.frame.size.height);

    CAGradientLayer *bgLayer = [BackgroundLayer greyGradient];
    bgLayer.cornerRadius = 5.0f;
    bgLayer.frame = CGRectMake(0, 0, size.width, size.height);
    mycell.cellBkView.backgroundColor = [UIColor colorWithPatternImage:[BackgroundLayer greyImageFromGradient:bgLayer]];
}

答案 1 :(得分:0)

试试这段代码:

CGFloat cellHeight = [self tableView:self.tableView heightForRowAtIndexPath:indexPath];