How to draw gradient background for uiview in iOS swift

This tutorial has been updated for X code 7.3 & swift 2.2

Gradients are becoming more popular with iOS 8 & swift. You can see them from logo of swift to many new apps build for iOS 8. And if you draw it programmatically then you don’t have to worry about scaling for different size iPhone or iPad.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set the values as follows and save it on your desktop.

new x code project

 

2. Go to view controller swift file & add initialize gradient layer

class ViewController: UIViewController {
let gradientLayer = CAGradientLayer()

Now add following code in view did load

override func viewDidLoad() {
    super.viewDidLoad()

    // 1
    self.view.backgroundColor = UIColor.greenColor()

    // 2
    gradientLayer.frame = self.view.bounds

    // 3
    let color1 = UIColor.yellowColor().CGColor as CGColorRef
    let color2 = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0).CGColor as CGColorRef
    let color3 = UIColor.clearColor().CGColor as CGColorRef
    let color4 = UIColor(white: 0.0, alpha: 0.7).CGColor as CGColorRef
    gradientLayer.colors = [color1, color2, color3, color4]

    // 4
    gradientLayer.locations = [0.0, 0.25, 0.75, 1.0]

    // 5
    self.view.layer.addSublayer(gradientLayer)

    // Do any additional setup after loading the view, typically from a nib.
}
  1. Set view background color to green color
  2. Gradient is applied to bounds of main view. See bounds vs frame explanation here.
  3. Four colors are created by different methods for explanation purpose. And added to gradient as array.
  4. Location of all colors is saved in gradient.
  5. Gradient is added to main view. If you create subview then add gradient to subview.

gradient layer

As you can see in the image gradient is between background of uiview & contents of uiview. If opacity of gradient is 1 then you cannot see background color & if opacity is 0 then you cannot see gradient. If gradient opacity is between 0 & 1 then you can create neat effects.

Now build and run app in iPhone 5s

vertical gradient
Download X code file
Challenge 1 : Create horizontal gradient

horrizontal gradient
Download Challenge 1 Solution
Challenge 2 : Create diagonal gradient

diagonal gradient
Download Challenge 2 Solution

Total 20 Votes
5

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?