【发布时间】:2017-01-10 10:33:02
【问题描述】:
对于 Swift 中的 iOS 应用程序,我正在使用编程约束,并希望将 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)
}
}
我认为我遇到的问题与我使用编程约束创建动画视图有关,然后我尝试通过将其框架设置为等于框架视图来添加渐变层。当我不使用编程约束时,此代码有效。有什么想法我错过/做错了吗?
【问题讨论】:
-
请把class关键字后面的冒号去掉
-
@Hamsternik 刚刚改了
标签: ios swift nslayoutconstraint cagradientlayer