對於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與程序的約束,然後我試圖通過設置其幀等於幀的視圖中添加漸變層的事實。此代碼的工作,當我不使用方案限制。任何想法我失蹤/做錯了?
請刪除* class *後的冒號關鍵字 – Hamsternik
@Hamsternik現在只需更改它 – Edward