Ravi Malviya Ravi Malviya - 1 year ago 146
Swift Question

how to apply gradient color layer in dynamic table cell at reload in ios

I want to create gradient kind of color code and set into dynamic table view cell which height vary according to data.
I used layer when I am going to add into layer of table cell. I need exact table view cell height after table data load.

-(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{

[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

return image;

this code can not able to create exact size image so it got blur.

Answer Source

Here u can find ur solution let me know if any issue

- (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]];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download