gpt4 book ai didi

ios - UIView 的水平渐变

转载 作者:搜寻专家 更新时间:2023-11-01 05:55:02 25 4
gpt4 key购买 nike

我正在尝试通过以下方式将水平渐变添加到 UIView

extension UIView {
func insertHorizontalGradient(_ color1: UIColor, _ color2: UIColor) {
let gradient = CAGradientLayer()
gradient.colors = [color1.cgColor, color2.cgColor]
gradient.transform = CATransform3DMakeRotation(CGFloat.pi / 2, 0, 0, 1)
gradient.frame = bounds
layer.insertSublayer(gradient, at: 0)
}
}


if let color1 = UIColor(hexString: "364190"), let color2 = UIColor(hexString: "699cf5"){
self.statusBarView.insertHorizontalGradient(color1, color2)
}

if let color1 = UIColor(hexString: "182395"), let color2 = UIColor(hexString: "5497f0"){
self.navigationBarView.insertHorizontalGradient(color1, color2)
}

但在 iPhone 6Plus 上,它不会应用于整个 UIView。但在 iPhone 6 上它是完美的。

enter image description here

最佳答案

每当 View 的框架发生变化时,您都必须更新渐变。使用扩展不是最好的解决方案,因为您必须在所有使用它的 UIView 实例中覆盖 UIView.layoutSubviews。相反,您可以将图层包装到 View 中:

@IBDesignable
public class GradientView: UIView {
private func createGradient() -> CAGradientLayer {
let gradient = CAGradientLayer()
gradient.transform = CATransform3DMakeRotation(.pi / 2, 0, 0, 1)
gradient.frame = bounds
layer.insertSublayer(gradient, at: 0)
return gradient
}

private var gradient: CAGradientLayer?

@IBInspectable
public var color1: UIColor? {
didSet {
updateColors()
}
}

@IBInspectable
public var color2: UIColor? {
didSet {
updateColors()
}
}

required public init?(coder: NSCoder) {
super.init(coder: coder)
gradient = createGradient()
updateColors()
}

override public init(frame: CGRect) {
super.init(frame: frame)
gradient = createGradient()
updateColors()
}

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

private func updateColors() {
guard
let color1 = color1,
let color2 = color2
else {
return
}

gradient?.colors = [color1.cgColor, color2.cgColor]
}
}

然后:

extension UIView {
func insertHorizontalGradient(_ color1: UIColor, _ color2: UIColor) -> GradientView {
let gradientView = GradientView(frame: bounds)
gradientView.color1 = color1
gradientView.color2 = color2
gradientView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

self.insertSubview(gradientView, at 0)
return gradientView
}
}

请注意,我已经制作了 View @IBDesignable,两种颜色 @IBInspectable,因此您实际上可以在 Storyboard/xib 中预览渐变。

关于ios - UIView 的水平渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51538572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com