How to set multiple gradient colour in UITableViewCell using CAGradientLayer in iOS?

橙三吉。 提交于 2019-12-08 11:18:28
Rajesh

This I can achieve with below code

TableViewCell.h

@interface TableViewCell : UITableViewCell
{
    UIImageView *imageView;
    UIView *viewGradient;
    CAGradientLayer *gradientLayer;
}

- (void)setImage:(UIImage *)image andColor:(UIColor *)color;

@end

TableViewCell.m

- (void)awakeFromNib {
    [self.contentView setFrame:CGRectMake(0, 0, 320, 44)];
        imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
    [imageView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth ];
            [self.contentView addSubview:imageView];

            viewGradient = [[UIView alloc] initWithFrame:self.contentView.bounds];
        [viewGradient setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth ];
            [self.contentView addSubview:viewGradient];
            gradientLayer = [CAGradientLayer layer];
            gradientLayer.frame = viewGradient.bounds;
            [gradientLayer setStartPoint:CGPointMake(0.0, 0.5)];
            [gradientLayer setEndPoint:CGPointMake(1.0, 0.5)];
            [viewGradient.layer insertSublayer:gradientLayer atIndex:0];
}
 - (void)setImage:(UIImage *)image andColor:(UIColor *)color
    {
        [imageView setImage:image];
        gradientLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[color CGColor], nil];
    }

ViewController.m

         - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        switch (indexPath.row)
        {
            case 0:
                [cell setImage:[UIImage imageNamed:@"Grass"] andColor:[UIColor whiteColor]];
                break;
            case 1:
                [cell setImage:[UIImage imageNamed:@"House"] andColor:[UIColor greenColor]];
                break;
            case 2:
                [cell setImage:[UIImage imageNamed:@"Sky"] andColor:[UIColor redColor]];
                break;

            default:
                break;
        }
        return cell;
    }

Refer to screenshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!