gpt4 book ai didi

ios - Swift:UIView 的背景渐变

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:00 26 4
gpt4 key购买 nike

我在尝试向 UIView 添加渐变背景时遇到问题。我对 UIView 进行了扩展,并添加了以下方法:

func setGradientBackground(colorTop: UIColor, colorBottom: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.frame = bounds

layer.insertSublayer(gradientLayer, at: 0)
}

然后我调用:

separatorView.setGradientBackground(colorTop: .clear, colorBottom: .red)

但它不起作用。 View 已呈现,但其背景完全清楚。我也尝试使用 CGColor

最佳答案

有两个问题:

  • 我需要设置起点和终点以提供渐变方向:

    func setGradientBackground(colorTop: UIColor, colorBottom: UIColor) {
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
    gradientLayer.locations = [0, 1]
    gradientLayer.frame = bounds

    layer.insertSublayer(gradientLayer, at: 0)
    }
  • 第二个问题是 CAGradientLayer 在 View 布局后生效。我解决了在 viewDidAppear 上调用 setGradientBackground() 的问题:

    override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    separatorView.setGradientBackground(colorTop: .clear, colorBottom: Colors.darkGrey)
    }

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

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