Search code examples
iosuitableviewinterface-builder

Is there a way to make gradient background color in the interface builder?


For my application I'm using a TableView and using customized UITableViewCells.

I customized my cells via interface builder, not programmatically. Is there a way to also make the background color of my customized cell a gradient in the interface builder?

Thanks.


Solution

  • To draw a gradient, you will have to subclass and override the drawRect programmatically:

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGContextSaveGState(context);
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGGradientRef gradient = CGGradientCreateWithColorComponents
                                 (colorSpace,
                                  (const CGFloat[8]){1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f},
                                  (const CGFloat[2]){0.0f,1.0f},
                                  2);
    
        CGContextDrawLinearGradient(context,
                                    gradient,
                                    CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMinY(self.bounds)),
                                    CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMaxY(self.bounds)),
                                    0);
    
        CGColorSpaceRelease(colorSpace);
        CGContextRestoreGState(context);
    }
    

    The easiest way, which keeps your cells in the interface builder, is probably to subclass a UIView to have it draw a gradient in its drawRect and place it in your cell behind the other subviews:

    GradientView *gradientView = [[GradientView alloc] init];
    gradientView.frame = cell.bounds;
    [cell addSubview:gradientView];
    [cell sendSubviewToBack:gradientView];
    

    However, the best way to do it is probably not to use the interface builder for this and make a subclass of UITableViewCell. For advanced customization, interface builders tend to only make things more complicated in my experience. That's up to personal preference though.