使用编程约束时如何将 CAGradientLayer 添加到 UIView [英] How to add a CAGradientLayer to a UIView when using programmatic constraints

查看:93
本文介绍了使用编程约束时如何将 CAGradientLayer 添加到 UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 Swift 中的 iOS 应用程序,我正在使用编程约束并想将 CAGradientLayer() 添加到 UIView().下面是我的代码,它不起作用.

For an iOS app in Swift, I am using programmatic constraints and would like to add a CAGradientLayer() to a UIView(). Below is my code which doesn't work.

   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,然后我尝试通过将其框架设置为等于框架视图来添加渐变层.当我不使用编程约束时,此代码有效.任何想法我错过/做错了什么?

The issue I am having I believe is related to the fact that I create animationView with programmatic constraints and I then try and add the gradient layer by setting its frame equal to the view of the frame. This code works when I don't use programmatic constraints. Any ideas what I am missing / doing wrong?

推荐答案

您添加到视图中的任何图层都不会在 AutoLayout 下进行管理,并且没有办法实现这一点.

Any layers that you add to the view will not be managed under AutoLayout and there isn't a way to make this happen.

您可以做的是将图层存储为属性(可能在视图控制器上).

What you can do is store the layer as a property (perhaps on the view controller).

然后在方法中...

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

在这种方法中,视图将拥有正确的框架,因此如果它发生了变化,您将需要相应地更新图层以拥有一个新框架.

In this method the view will have it's proper frame so if it has changed you will need to update the layer to have a new frame accordingly.

这篇关于使用编程约束时如何将 CAGradientLayer 添加到 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆