在UIView上运行渐变不起作用

时间:2016-07-16 11:11:11

标签: ios swift uiview quartz-core cagradientlayer

我正在尝试以编程方式向UIView添加渐变,但它无法正常工作。它似乎根本没有颜色。我附上了相关代码以及截图。注意我应用渐变的底部正方形。有人能帮助我弄清楚我在这里做错了什么吗?

Screenshot

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)
}

2 个答案:

答案 0 :(得分:7)

您的渐变未显示,因为在自动布局运行之前,bounds的{​​{1}}将不会设置。覆盖sundayView并在那里设置渐变框架。

将此属性添加到viewController:

viewDidLayoutSubviews

var sundayGradient: CAGradientLayer? 中将setupSundayView保存到该媒体资源中:

gradient

然后在let gradient = CAGradientLayer() sundayGradient = gradient

中设置框架
viewDidLayoutSubviews

答案 1 :(得分: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)
}