Swift: Gradient splits on rotation

谁都会走 提交于 2020-02-05 13:53:45

问题


In short, I have a gradient that is a mix of Dark Blue and Black. The gradient looks beautiful, however when I rotate the screen and put it in landscape, the two colors split and half of the screen has a blue background and the other half is black. Figuring I didn't do it right, I copied codes from these two sources:

YouTube video https://www.youtube.com/watch?v=pabNgxzEaRk

Website http://blog.apoorvmote.com/gradient-background-uiview-ios-swift/

This is my code:

    let topColor = UIColor(red: 28/255.0, green: 25/255.0, blue: 127/255.0, alpha: 1)
    let bottomColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 25/255.0, alpha: 1)

    let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor]
    let gradientLocations: [Float] = [0.0, 1.0]

    let gradientLayer: CAGradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientColors
    gradientLayer.locations = gradientLocations

    gradientLayer.frame = self.view.bounds
    self.view.layer.insertSublayer(gradientLayer, atIndex: 0)

Can someone point me in the right direction to stop my gradient from splitting in two?


回答1:


Keep in mind that when changing screen orientation all view's bounds change as well (assuming you are using auto layout) but the same thing is not applied on programmatically added layers. So in your case gradient layer still has the frame which is set based on old view bounds before rotation. To solve this I suggest subclassing your gradient view and update gradient layer frame in layoutSubviews function which is called on each view bounds change.

class GradientView: UIView {

    let gradientLayer = CAGradientLayer()

    override func awakeFromNib() {
        gradientLayer.frame = self.bounds
        gradientLayer.colors = yourColors
        gradientLayer.locations = yourLocations
        self.layer.addSublayer(gradientLayer)
    }

    override func layoutSubviews() {
        gradientLayer.frame = self.bounds
    }
}



回答2:


You only need to override layoutSubview method to Autoresize your gradient view with respect to your device's view

Write only,

override func viewDidLayoutSubviews() {
    gradientLayer.frame = self.view.bounds
}

I tried this and its working fine. Hope this help you.



来源:https://stackoverflow.com/questions/37880343/swift-gradient-splits-on-rotation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!