2017-01-22 68 views
-2

我想在我的应用程序中使用CAGradientLayer。动画视图的子视图不能与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元素,它们是可见的,但是当我尝试添加一些:我在的viewController的视图的子层的指数0插入CAGradientLayer动画(在点击按钮或更改文本时动画标签的阿尔法),它不起作用。该按钮的选择器触发,然后动画块执行......但没有任何反应。我尝试了最明显的解决方案 - 创建一个单独的视图并将其添加为子视图,但结果不会改变。控制器上的所有子视图都将添加到viewDidLoad的主视图中。也许我错过了关于CALayers的一些事情?

+0

我没有看到任何“动画块”。你在说什么? – matt

+0

@matt我在谈论UIView.animate(withDuration:<#T ## TimeInterval#>,动画:<#T##() -> Void#>),它只是在代码中的另一个地方。它会自动触发,但子视图没有任何反应。例如,我在动画块中将label.alpha设置为0,并且该行正在执行。但标签没有真正发生,它仍然可见! – Kmkrn

+0

但是您需要在_question_中显示_actual code_。为了帮助解决问题,我需要重新解决问题。所以请展示更多你的代码。 – matt

回答

0

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

0

在我的原代码,我在viewWillLayoutSubviews()添加标签和其它子视图

有一点要记住的是,viewWillLayoutSubviews被称为很多很多次在应用程序的生命周期。所以你可能一直在“添加标签和其他子视图”。这听起来不太好。