问题
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?
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()
}
}
回答1:
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.
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.
来源:https://stackoverflow.com/questions/37212423/making-gradient-background-in-swift-the-right-way