0

When I put the device in mode landscape, the background is set wrong. How do I fix it? I also could use to know how to put the entire application in landscape mode.

override func viewDidLoad() {
    super.viewDidLoad()
    //BACKGROUND FONDO
    //A linear Gradient Consists of two colours: top colour and bottom colour
    let topColor = UIColor(red: 15.0/255.0, green: 118.0/255.0, blue: 128.0/255.0, alpha: 1.0)
    let bottomColor = UIColor(red: 84.0/255.0, green: 187.0/255.0, blue: 187.0/255.0, alpha: 1.0) 

    //Add the top and bottom colours to an array and setup the location of those two.
    let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor]
    let gradientLocations: [CGFloat] = [0.0, 1.0]

    //Create a Gradient CA layer
    let gradientLayer: CAGradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientColors
    gradientLayer.locations = gradientLocations

    gradientLayer.frame = self.view.bounds
    self.view.layer.insertSublayer(gradientLayer, atIndex: 0)
}    //FIN BACKGROUND GRADIENT
Tobi Nary
  • 4,566
  • 4
  • 30
  • 50

2 Answers2

1

In your case gradient is a Layer, not View. It means that it will not resize or change position while the containing layer changes (e.g. during rotation). You have to change the frame of the sublayer manually during rotation.

Piotr Tobolski
  • 1,326
  • 7
  • 22
1
var gradientLayer = CAGradientLayer()

override func viewDidLoad() {
    super.viewDidLoad()
    createGredientBackground()
}

override func viewWillLayoutSubviews() {
     super.viewWillLayoutSubviews()
     gradientLayer.frame = view.layer.bounds
}


func createGredientBackground() {

     let colorTop =  UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
     let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).cgColor
        
     gradientLayer.colors = [colorTop, colorBottom]
     gradientLayer.locations = [0.0, 1.0]
     gradientLayer.frame = self.view.bounds
                
     self.view.layer.insertSublayer(gradientLayer, at:0)
}
Dhara Patel
  • 396
  • 3
  • 9