1

I recently fixed a bug with gradient filled backgrounds that occurs when I rotate the iPad.

I found that the gradient fill was the wrong size after rotation, leading to blocks of the screen not having the proper fill.

I detect device rotation as recommended in this question and invoke the following method each time a device orientation change is detected.

It works perfectly, but seems kind of kludgy to me.

My question is simple; Is this a best practice solution? What should I have done instead?

Edit: - per comments. Better code ?

/// Adds a gradient background layer to the root of the layer stack, and removes any other one that may already be there
+ (void) addGradientBackground:(UIView *)view {

    dispatch_async(dispatch_get_main_queue(), ^{
        CALayer *vl = view.layer.sublayers[0];
        if ([vl isKindOfClass:[CAGradientLayer class]]) {
            [vl removeFromSuperlayer];
        }

        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = view.bounds;
        gradient.colors = [NSArray arrayWithObjects:(id)[[UICustomColor featherColor] CGColor], (id)[[UICustomColor marineColor] CGColor], nil];
        gradient.startPoint = CGPointMake(0.0, 0.25);
        gradient.endPoint = CGPointMake(1, 0.75);
        [view.layer insertSublayer:gradient atIndex:0];
    });
}
Community
  • 1
  • 1
Curt Eckhart
  • 455
  • 5
  • 11

0 Answers0