Daniel Dramond Daniel Dramond - 1 month ago 4
Swift Question

How do I add a label on top of a gradient?

I have a very basic UICollectionView. Inside my CollectionViewCell, I have a "thumbnailImage" which is just an image. I would like to have a gradient layer that fades from black, to a clear color BUT I would also like to have a UILabel ON TOP of this CAGradient and not underneath. The label is the "MovieTitle". I am programmatically doing everything, including the constraints. How do I perform this? Here is my code

let myView: UIView = {
let view = UIView()
return view
}()

let gradientView: CAGradientLayer = {
let grad = CAGradientLayer()
grad.colors = [UIColor.white.cgColor, UIColor.red.cgColor]
grad.locations = [0.7, 1.2]
return grad
}()

func setupViews() {
thumbnailImageView.addSubview(movieTitle)
addSubview(thumbnailImageView)
thumbnailImageView.addSubview(dividerLine)
thumbnailImageView.addSubview(myView)
myView.layer.addSublayer(gradientView)

addConstrainsWithFormat(format: "H:|[v0]|", views: thumbnailImageView)
addConstrainsWithFormat(format: "V:|[v0]|", views: thumbnailImageView)

thumbnailImageView.addConstrainsWithFormat(format: "H:|[v0]|", views: myView)
thumbnailImageView.addConstrainsWithFormat(format: "V:|[v0]|", views: myView)

thumbnailImageView.addConstrainsWithFormat(format: "H:|[v0]|", views: dividerLine)
thumbnailImageView.addConstrainsWithFormat(format: "V:[v0(0.75)]|", views: dividerLine)

thumbnailImageView.addConstrainsWithFormat(format: "H:|-16-[v0]-16-|", views: movieTitle)
thumbnailImageView.addConstrainsWithFormat(format: "V:[v0(25)]-8-|", views: movieTitle)
}

Answer

Try to change the order of your views so that label appears above the view with gradient inside:

myView.layer.addSublayer(gradientView)
thumbnailImageView.addSubview(myView)
thumbnailImageView.addSubview(movieTitle)
thumbnailImageView.addSubview(dividerLine)
addSubview(thumbnailImageView)

You can also insert layers and views below or above already existing layers/views in your hierarchy:

view.insertSubview(subview, at: 0)
view.insertSubview(subview, belowSubview: existingView)
view.insertSubview(subview, aboveSubview: existingView)

layer.insertSublayer(gradientLayer, at: 0)
layer.insertSublayer(gradientLayer, below: anotherLayer)
layer.insertSublayer(gradientLayer, above: anotherLayer)
Comments