首页 > 解决方案 > Swift:UIView 的背景渐变

问题描述

我在尝试将渐变背景添加到 UIView. 我做了一个extensionUIView添加了以下方法:

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)

但它不起作用。视图已呈现,但其背景完全清晰。我也试过了CGColor

标签: iosswiftuiview

解决方案


有2个问题:

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

    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视图布局后生效。我解决了这个setGradientBackground()问题viewDidAppear

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

推荐阅读