kitchen800
kitchen800

Reputation: 227

Push gradient layer to background swift

My app has a gradient layer that I made in code. However when I display this onscreen it covers all the other components and hides my buttons, labels and images.

How do I push this layer back so its the background of the view?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //creating color gradient
    let topColor = UIColor(red: 69/255, green: 140/255, blue: 68/255, alpha: 1).CGColor
    let bottomColor = UIColor(red: 143/255, green: 239/255, blue: 141/255, alpha: 1).CGColor
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.view.frame
    gradientLayer.colors = [topColor,bottomColor]
    gradientLayer.locations = [0.1,1.0]
    self.view.layer.addSublayer(gradientLayer)   
}

Upvotes: 7

Views: 5693

Answers (3)

Jitendra Solanki
Jitendra Solanki

Reputation: 772

You can add any of the subviews you have at any index as:

self.view.layer.insertSublayer(yourLayer, at: 0)

at also can be used as atIndex, and it means the indexPath of the view (from the view hierarchy), where you want to add your subview at.

Upvotes: 1

Aashish
Aashish

Reputation: 2696

We can also add a subview below or above any other views using insertSubview

self.view.insertSubview(subview1_name, belowSubview: subview2_name)
self.view.insertSubview(subview1_name, aboveSubview: subview2_name)

Upvotes: 1

Yannick
Yannick

Reputation: 3278

You can insert a sublayer at a specific index.

self.view.layer.insertSublayer(gradientLayer, at: 0)

Upvotes: 22

Related Questions