在Swift中制作渐变背景-正确的方法 [英] Making Gradient Background in Swift - The Right Way

查看:379
本文介绍了在Swift中制作渐变背景-正确的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的渐变背景代码.当我将其应用到视图中时,它会将我的所有东西都隐藏在该VC上,就像它在前面一样,其他所有东西都向后推.如何制作不干扰元素的渐变视图?

This is my code for a gradient background. When I apply it on my view, it hides all my stuff on that VC, like it's on the front and everything else is pushed back. How can I make a gradient view that is not interfering with my elements?

我正在使用@IBDesignable只是为了查看故事板中的外观.

I'm using @IBDesignable just to see how is it looking in Storyboard.

import UIKit

@IBDesignable
class GradientView: UIView {

    private let gradientLayer = CAGradientLayer()

    var color1 = ColorPalette.GrdTop
    var color2 = ColorPalette.GrdBottom

    override init(frame: CGRect) {
        super.init(frame: frame)
        configureGradient()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureGradient()
    }

    func configureGradient() {
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        updateColors()
        layer.addSublayer(gradientLayer)
    }

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

    private func updateColors() {
        gradientLayer.colors = [color1.CGColor, color2.CGColor]
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        configureGradient()
    }
}

推荐答案

就像在前面一样,其他所有东西都被推回

like it is on the front and everything else is pushed back

因为在前面.考虑一下这段代码:

Because it is on the front. Think about this line of your code:

layer.addSublayer(gradientLayer)

这会将渐变层置于该层的所有其他子层的前面.视图的子视图由其层的子层显示,因此渐变层覆盖了该视图的当前子视图.

That puts the gradient layer in front of all other sublayers of this layer. Subviews of a view are displayed by sublayers of its layer, so the gradient layer covers this view's current subviews.

如果愿意(insertSublayer:atIndex:),可以将图层一直插入到背面.不过,一种优雅的解决方案是实现此视图的layerClass类方法返回CAGradientLayer.现在,您无需在GradientView中添加渐变;相反,您的GradientView 渐变,您可以根据需要配置该渐变.

You can insert your layer all the way at the back if you like (insertSublayer:atIndex:). The elegant solution, though, is to implement the layerClass class method for this view to return a CAGradientLayer. Now you won't have to add a gradient to your GradientView; instead, your GradientView is a gradient and you can just configure that gradient as desired.

这篇关于在Swift中制作渐变背景-正确的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆