How to resize a CAGradientLayer after rotation?

前端 未结 2 650
醉话见心
醉话见心 2021-02-19 03:06

I\'m adding a CAGradientLayer to a view. When the view is auto-resized (such as after a rotation) the gradient layer is not resized. Can the gradient be set to auto

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-19 03:49

    Here are two different ways to fix your problem.

    1. Make gradientLayer an instance variable instead of a local variable. Then, override layoutSubviews in your view class to set the frame of the gradient layer:

      - (void)layoutSubviews {
          [super layoutSubviews];
          _gradientLayer.frame = self.bounds;
      }
      
    2. Create a subclass of UIView named GradientView, and override its +layerClass method to return [CAGradientLayer class]. Use this view to draw your gradient instead of using a layer directly. Then set the gradient view's autoresizingMask (or add constraints to it if you are using auto layout). See this answer for an example.

    Creating the GradientView class will also make the resizing behave correctly during rotation, so I recommend that solution.

提交回复
热议问题