Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)   
}
like image 920
kitchen800 Avatar asked Jan 25 '17 11:01

kitchen800


3 Answers

You can insert a sublayer at a specific index.

self.view.layer.insertSublayer(gradientLayer, at: 0)
like image 155
Yannick Avatar answered Nov 14 '22 08:11

Yannick


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)
like image 42
Aashish Avatar answered Nov 14 '22 10:11

Aashish


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.

like image 1
Jitendra Solanki Avatar answered Nov 14 '22 09:11

Jitendra Solanki