如何使我的颜色渐变显示在我的自定义UIView Swift中



我有一个自定义的UIView类,添加了UIImageView和UILabel子视图,但我无法在它们上面显示颜色渐变。

这是我的自定义UIView类:

//
//  HomeTitleView.swift
//  Find My Lift
//
//  Created by Stephen Learmonth on 13/11/2020.
//  Copyright © 2020 Stephen Learmonth. All rights reserved.
//
import UIKit
class HomeTitleView: UIView {
// MARK: - Properties

private let homeTitleImageView: UIImageView = {
let hiv = UIImageView()
hiv.image = UIImage(named: "Stephen")
hiv.contentMode = .scaleAspectFill
hiv.clipsToBounds = true
hiv.setHeight(height: 180)
hiv.backgroundColor = .clear
return hiv
}()

var homeTitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 25)
label.backgroundColor = .clear
label.textColor = .white
return label
}()
// MARK: - Lifecycle

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

configureUI()
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

// MARK: - Helper Functions

private func configureUI() {

let gradient = CAGradientLayer()
gradient.colors = [UIColor.clear.cgColor , UIColor.black.cgColor]
gradient.locations = [0.85, 1]
self.layer.addSublayer(gradient)
gradient.frame = self.bounds

self.addSubview(homeTitleImageView)
homeTitleImageView.anchor(top: safeAreaLayoutGuide.topAnchor, left: leftAnchor,
bottom: bottomAnchor, right: rightAnchor,
paddingTop: 0, paddingLeft: 0,
paddingBottom: 0, paddingRight: 0)

self.addSubview(homeTitleLabel)
homeTitleLabel.anchor(left: leftAnchor, bottom: bottomAnchor,
paddingLeft: 12, paddingBottom: 30)



}
}

我缺乏一些层和子视图的知识,无法理解为什么它不起作用。感谢您的帮助。

移动此行

self.layer.addSublayer(gradient)

configureUI结束和

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

最新更新