Allan Jiang Allan Jiang - 1 year ago 193
iOS Question

Programmatically create a UIView with color gradient

What I'm trying to do is generating a view with gradient color background (A solid color to transparent) at runtime. Is there a way of doing that?

Answer Source


UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 50.0f)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
//use startPoint and endPoint to change direction of gradient (


let view: UIView = UIView(frame: CGRectMake(0.0, 0.0, 320.0, 50.0))
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.whiteColor().CGColor, UIColor.blackColor().CGColor]
view.layer.insertSublayer(gradient, atIndex: 0)
//use startPoint and endPoint to change direction of gradient (

If there are any other views added onto this UIView (such as a UILabel), you may want to consider setting the background color of those UIView’s to [UIColor clearColor] so the gradient view is presented instead of the background color for sub views. Using clearColor has a slight performance hit.