2017-01-10 43 views
0

對於Swift中的iOS應用程序,我使用編程約束並希望將CAGradientLayer()添加到UIView()。下面是我的代碼不起作用。如何使用編程約束將CAGradientLayer添加到UIView

import UIKit 

    class ViewController: UIViewController { 

     let animationView: UIView = { 
      let view = UIView() 
      view.translatesAutoresizingMaskIntoConstraints = false 
      return view 
     }() 

     override func viewDidLoad() { 
      super.viewDidLoad() 

      view.addSubview(animationView) 
      setupAnimationView() 
      animationView.addGradientLayer() 
     } 

     func setupAnimationView() { 
      animationView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true 
      animationView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true 
      animationView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true 
      animationView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true 
     } 
    } 

    extension UIView { 

     func addGradientLayer() { 
      let color1 = UIColor(red: 251/255, green: 55/255, blue: 91/255, alpha: 1.0) 
      let color2 = UIColor(red: 1.0, green: 70/255, blue: 0, alpha: 1.0) 
      let gradientLayer = CAGradientLayer() 
      gradientLayer.name = "gradientLayer" 
      gradientLayer.frame = self.frame 
      gradientLayer.colors = [color1.cgColor, color2.cgColor] 
      self.layer.insertSublayer(gradientLayer, at: 0) 
     } 
    } 

我有我相信這個問題是關係到我創建animationView與程序的約束,然後我試圖通過設置其幀等於幀的視圖中添加漸變層的事實。此代碼的工作,當我不使用方案限制。任何想法我失蹤/做錯了?

+0

請刪除* class *後的冒號關鍵字 – Hamsternik

+0

@Hamsternik現在只需更改它 – Edward

回答

2

要添加到視圖的任何層不會自動版式和下管理沒有辦法做到這一點。

你可以做什麼是層存儲爲一個屬性(大概是在視圖控制器)。

的方法

則...

override func viewDidLayoutSubviews() { 
    super.viewDIdLayoutSubviews() 
    // update the layers frame based on the frame of the view. 
} 

在這種方法的看法將是適當的框架,所以如果它已經改變了,你將需要更新的層相應地有一個新的框架。

0

layoutIfNeeded()應立即打電話最新意見。

animationView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true 
animationView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true 
animationView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true 
animationView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true 

view.layoutIfNeeded() 
+0

這沒有奏效 – Edward

+0

您是否設法繪製漸變? – Matt

+0

是啊,我想我在我viewDidLoad中排序錯誤 - 感謝您的幫助@馬特 – Edward

1

您應該更改下面的代碼行:

gradientLayer.frame = self.frame 

到:

gradientLayer.frame = bounds 

這是因爲框架和邊界沒有使用相同的座標空間是很重要的。幀是上海華的座標空間中,而邊界是視圖的內部座標空間。

你也可以告訴正是爲你的漸變的起點和終點將您gradientLayer您層之前:

gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) 
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) 
layer.addSublayer(gradientLayer)