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.
Just as you can declare the background of an element to be a solid color in CSS, you can also declare that background to be a gradient.
Select the Gradient tool in the toolbar. In the selected artwork you'll see the gradient annotator, which shows the gradient slider and the color stops. Double-click a color stop on the artwork to edit the color, drag the color stops, click beneath the gradient slider to add new color stops, and more.
This works for Swift 3.0: (Updated for Swift 4.0)
@IBDesignable final class GradientView: UIView { @IBInspectable var startColor: UIColor = UIColor.clear @IBInspectable var endColor: UIColor = UIColor.clear override func draw(_ rect: CGRect) { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: superview!.frame.size.width, height: superview!.frame.size.height) gradient.colors = [startColor.cgColor, endColor.cgColor] gradient.zPosition = -1 layer.addSublayer(gradient) } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With