动画视图的子视图无法与CAGradientLayer

时间:2017-01-22 18:13:15

标签: ios uiviewanimation cagradientlayer

我想在我的应用中使用CAGradientLayer。我在viewController的子视图的索引0处插入CAGradientLayer:

class ViewController: UIViewController {
var label: UILabel!

override func viewDidLoad() {
    let width = view.frame.size.width
    let height = view.frame.size.height
    super.viewDidLoad()
    label = UILabel(frame: CGRect(x: 30, y: 80, width: width/4, height: height/20))
    label.backgroundColor = UIColor.yellow
    label.textColor = UIColor.white
    label.text = "label"
    label.alpha = 0
    view.addSubview(label)
    let hideButton = UIButton.init(type: .system)
    hideButton.frame = CGRect(x: width/2 - 15, y: label.frame.origin.y + 50, width: width/4, height: 30)
    hideButton.setTitle("Hide", for: .normal)
    hideButton.backgroundColor = UIColor.red
    hideButton.addTarget(self, action: #selector(ViewController.fadeOutLabel), for: .touchUpInside)
    view.addSubview(hideButton)

    let gradientButton = UIButton.init(type: .system)
    gradientButton.frame = CGRect(x: width/2 - 15, y: hideButton.frame.origin.y + 50, width: width/4, height: 30)
    gradientButton.setTitle("add gradient", for: .normal)
    gradientButton.backgroundColor = UIColor.red
    gradientButton.addTarget(self, action: #selector(ViewController.updateSubviews), for: .touchUpInside)
    view.addSubview(gradientButton)

}

func updateSubviews() {
    UIView.animate(withDuration: 0.3, animations: {
        self.label.alpha = 1
        let gradientSublayer = self.makeGradientLayer()
        self.view.layer.insertSublayer(gradientSublayer, at: 0)
        }, completion: nil)
}

func makeGradientLayer() -> CAGradientLayer{
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = UIScreen.main.bounds
    let primaryColor = UIColor.yellow
    let secondaryColor = UIColor.green
    gradientLayer.colors = [primaryColor.cgColor, secondaryColor.cgColor]
    return gradientLayer
}

func fadeOutLabel(){
    print("touch received")
    UIView.animate(withDuration: 0.3, animations: { 
        self.label.alpha = 0
        }) { (finished) in
            print("animation finished")
    }
}

}

但是,我在屏幕上有其他UI元素,并且它们是可见的,但是当我尝试添加一些动画时(在点击按钮或更改其文本时动画标签' s),它不会工作。按钮的选择器触发,然后动画块执行......但没有任何反应。我尝试过最明显的解决方案 - 创建一个单独的视图并将其添加为子视图,但结果不会发生变化。控制器上的所有子视图都将添加到viewDidLoad中的主视图中。也许我错过了一些关于CALayers的事情?

1 个答案:

答案 0 :(得分:0)

在我的原始代码中,我在viewWillLayoutSubviews()中添加了标签和其他子视图。我将所有内容移动到viewDidLoad()并且动画开始起作用。不幸的是,我无法在示例项目中重现这一点。还不确定我错了。