如何将我的渐变层作为子层添加到我的视图中,具有相同的大小,我想在其他类中使用它?
我试着用“self.bounds”来做,但没有成功。 如果我给它严格的尺寸,例如: gradientLayer.frame = CGRect(x: 0, y: 0, width: 100, height: 100) - 它会工作,但我需要与我的视图相同的大小。
final class ShimmerLabel: UIView {
private lazy var backShimmerTextLabel: UILabel = {
let label = UILabel()
label.text = "Shimmer"
label.textColor = UIColor(red: 65/255, green: 65/255, blue: 65/255, alpha: 1)
label.font = UIFont.systemFont(ofSize: 50)
label.textAlignment = .center
return label
}()
private lazy var frontShimmerTextLabel: UILabel = {
let label = UILabel()
label.text = "Shimmer"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 50)
label.textAlignment = .center
return label
}()
init() {
super.init(frame: .zero)
configureGradientLayer()
configureLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureGradientLayer() {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
gradientLayer.locations = [0, 1]
gradientLayer.frame = bounds // Dont work with bounds :((
layer.addSublayer(gradientLayer)
}
private func configureLayout() {
addSubview(backShimmerTextLabel)
backShimmerTextLabel.snp.makeConstraints { make in
make.width.height.equalToSuperview()
}
addSubview(frontShimmerTextLabel)
frontShimmerTextLabel.snp.makeConstraints { make in
make.width.height.equalToSuperview()
}
}
}
您可以像这样使用视图的“基础”层作为
CAGradientLayer
:
// use the "base" layer as a gradient layer
lazy var gradientLayer: CAGradientLayer = self.layer as! CAGradientLayer
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
所以你的班级变成:
final class ShimmerLabel: UIView {
private lazy var backShimmerTextLabel: UILabel = {
let label = UILabel()
label.text = "Shimmer"
label.textColor = UIColor(red: 65/255, green: 65/255, blue: 65/255, alpha: 1)
label.font = UIFont.systemFont(ofSize: 50)
label.textAlignment = .center
return label
}()
private lazy var frontShimmerTextLabel: UILabel = {
let label = UILabel()
label.text = "Shimmer"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 50)
label.textAlignment = .center
return label
}()
// use the "base" layer as a gradient layer
lazy var gradientLayer: CAGradientLayer = self.layer as! CAGradientLayer
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
init() {
super.init(frame: .zero)
configureGradientLayer()
configureLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureGradientLayer() {
gradientLayer.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
gradientLayer.locations = [0, 1]
}
private func configureLayout() {
addSubview(backShimmerTextLabel)
backShimmerTextLabel.snp.makeConstraints { make in
make.width.height.equalToSuperview()
}
addSubview(frontShimmerTextLabel)
frontShimmerTextLabel.snp.makeConstraints { make in
make.width.height.equalToSuperview()
}
}
}
渐变将始终填充视图框架。无需添加子层。