在 UIView 上应用渐变不起作用

Apply gradient on a UIView not working

我正在尝试以编程方式向 UIView 添加渐变,但它不起作用。它只是看起来根本没有颜色。我附上了相关代码和截图。注意我正在应用渐变的底部正方形。有人可以帮我弄清楚我在这里做错了什么吗?

let sundayView = UIView()

override func viewDidLoad() {
    super.viewDidLoad()
    setupViews()
    setupSundayView()
}

func setupViews() {
    sundayView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(sundayView)
}

func setupSundayView() {
    sundayView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activateConstraints([
        sundayView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor),
        sundayView.topAnchor.constraintEqualToAnchor(fridayView.bottomAnchor, constant: 16.0),
        sundayView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant: -8.0),            
        sundayView.heightAnchor.constraintEqualToAnchor(mondayView.heightAnchor),
        sundayView.widthAnchor.constraintEqualToAnchor(mondayView.widthAnchor)
        ])

    let gradient = CAGradientLayer()
    gradient.frame = sundayView.bounds
    gradient.colors = [
        UIColor(red:1.00, green:0.37, blue:0.23, alpha:1.0).CGColor,
        UIColor(red:1.00, green:0.16, blue:0.41, alpha:1.0).CGColor
    ]
    sundayView.layer.insertSublayer(gradient, atIndex: 0)
}

你好像忘了给渐变层添加locations,试试这个:

func setupSundayView() {
    sundayView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activateConstraints([
        sundayView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor),
        sundayView.topAnchor.constraintEqualToAnchor(fridayView.bottomAnchor, constant: 16.0),
        sundayView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant: -8.0),            
        sundayView.heightAnchor.constraintEqualToAnchor(mondayView.heightAnchor),
        sundayView.widthAnchor.constraintEqualToAnchor(mondayView.widthAnchor)
        ])

    let gradient = CAGradientLayer()
    gradient.frame = sundayView.bounds
    gradient.colors = [
        UIColor(red:1.00, green:0.37, blue:0.23, alpha:1.0).CGColor,
        UIColor(red:1.00, green:0.16, blue:0.41, alpha:1.0).CGColor
    ]
    gradient.locations = [0.0, 0.5]
    sundayView.layer.insertSublayer(gradient, atIndex: 0)
}

您的渐变没有显示,因为 sundayViewboundsAuto Layout 运行之前不会设置。覆盖 viewDidLayoutSubviews 并在那里设置渐变框架。

将此 属性 添加到您的 viewController:

var sundayGradient: CAGradientLayer?

setupSundayView中保存gradient到属性:

let gradient = CAGradientLayer()
sundayGradient = gradient

然后在viewDidLayoutSubviews中设置frame:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    sundayGradient?.frame = sundayView.bounds
}