It is generally known to use CAGradientLayer to realize View gradient, but in the actual process, there may be some pits, here is mainly to solve the two pits, but also to solve other similar problems to provide some ideas.

1. Solve the problem that the text or pictures that need to be displayed such as UIButton and UILabel are covered with gradient color
2, according to a state of the interface, to dynamically change the View of the gradient failure

In order to make it easier for you to use the code, create a classification. There are two main cases for processing. One is to insert the gradient into the bottom layer of the layer when the gradient is set for the first time, so that the content added to the initial View will not be affected. To achieve the View will not have multiple gradients, but also to solve the problem of changing gradients failure and gradient coverage of the View content, kill two birds with one stone.

- (void)kk_addGradientLayerWithStartColor:(UIColor *)startColor endColor:(UIColor *)endColor startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint { CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor]; GradientLayer. Locations = @ [@ 0.0, @ 1.0]; gradientLayer.startPoint = startPoint; gradientLayer.endPoint = endPoint; gradientLayer.frame = self.bounds;if (self.layer.sublayers.count == 0) {
           [self.layer insertSublayer:gradientLayer atIndex:0];
       } else {
           for (int i = 0; i < self.layer.sublayers.count; i++) {
               if ([self.layer.sublayers[i] isKindOfClass:[CAGradientLayer class]]) {
                  NSMutableArray *arrs = [NSMutableArray arrayWithArray:self.layer.sublayers];
                  [arrs replaceObjectAtIndex:i withObject:gradientLayer];
                  self.layer.sublayers = [NSArray arrayWithArray:arrs];
                  break;
               } else if (i == (self.layer.sublayers.count - 1)) {
                  [self.layer insertSublayer:gradientLayer atIndex:0];
                   break;
               }
           }
       }
}

- (void)kk_addGradientLayerWithStartColor:(UIColor *)startColor endColor:(UIColor *)endColor {
    return[the self kk_addGradientLayerWithStartColor: startColor endColor: endColor the startPoint: CGPointMake (0.0, 0.0) the endPoint: CGPointMake (1.0, 0.0)]; } `Copy the code