无法在渐变屏幕上看到视图元素

时间:2017-11-08 19:58:30

标签: ios swift

具有渐变背景的ViewHelper类

class ViewHelper: UIView{
class func setBackGroundColor(view: UIView){
    let startColor = UIColor(red:0.84, green:0.82, blue:0.80, alpha:1.0)
    let endColor = UIColor(red:0.19, green:0.26, blue:0.32, alpha:1.0)
    let newLayer = CAGradientLayer()
    newLayer.colors = [startColor.cgColor,endColor.cgColor]
    newLayer.frame = view.frame
    view.layer.addSublayer(newLayer)
}

和我设置它的MainClass

class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    ViewHelper.setBackGroundColor(view: self.view)
}

当我插入任何视图元素时,它是不可见的,只是我的渐变屏幕。 enter image description here

2 个答案:

答案 0 :(得分:1)

你可以简单地改变这个:

let newLayer = CAGradientLayer()

到此:

let newLayer = CAGradientLayer()
newLayer.zPosition = -1

但是,您的视图最好直接将渐变图层作为其图层(通过其layerClass属性)托管。

答案 1 :(得分:0)

您要在顶部添加图层newLayer

但你应该做的是将图层添加为最后一层作为底层

insertSublayer(_ layer: CALayer, at: UInt32)应该对您有所帮助

更好的方法可能是:

class ViewController: UIViewController {

    let gradientLayer = CAGradientLayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let startColor = UIColor(red:0.84, green:0.82, blue:0.80, alpha:1.0)
        let endColor = UIColor(red:0.19, green:0.26, blue:0.32, alpha:1.0)

        gradientLayer.colors = [startColor.cgColor,endColor.cgColor]
        view.layer.insertSublayer(gradientLayer, at: 0)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        gradientLayer.frame = view.frame
    }
}