如何以编程方式快速使用CAGradientLayer为UIView(子视图)设置渐变?

问题描述 投票:0回答:1
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(container)
        container.customAcnhor(top: view.topAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 350)

    }

    let container : UIView = {
        var view = UIView()
        let gradient = CAGradientLayer()
        gradient.frame = view.bounds
        gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
        view.layer.insertSublayer(gradient, at: 0)

        return view
    }()
}

代码上下文

上面的类有一个container,它是UIView类型,其中包含一个CAGradientLayer。我正在尝试将渐变显示到subview,在其中将此container(subview)添加到主视图中。下面是一个有关如何实现此目标的类似示例。图像上的蓝色需要具有我的自定义渐变。有人可以帮我解决这个问题吗?

I want the gradient to be on the blue part of the sub-view as something similar shown in the image.

ios swift uiview subview cagradientlayer
1个回答
0
投票

布局gradient layer后,可能必须再次设置container view的框架。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(container)
        container.customAcnhor(top: view.topAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 350)
        gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
        gradient.frame = view.bounds
    }
    let gradient = CAGradientLayer()

    lazy var container : UIView = {
        var view = UIView()
        view.layer.insertSublayer(gradient, at: 0)
        return view
    }()
}
© www.soinside.com 2019 - 2024. All rights reserved.