在模式环境中无法正确看到背景渐变

时间:2016-03-08 13:42:39

标签: ios swift

当我将设备置于模式环境中时,背景设置错误。我如何解决它?我也可以用来知道如何将整个应用程序置于横向模式。

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

2 个答案:

答案 0 :(得分:1)

在你的情况下,渐变是一个图层,而不是视图。这意味着当包含层改变时(例如在旋转期间)它不会调整大小或改变位置。您必须在旋转期间手动更改子图层的框架。

答案 1 :(得分:0)

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)
}