2017-01-22 61 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被稱爲很多很多次在應用程序的生命週期。所以你可能一直在「添加標籤和其他子視圖」。這聽起來不太好。