Search code examples
iosiphoneautolayoutcalayercagradientlayer

Autolayout not pass to sublayer


I m using Xamarin for iOS v5.8.3(build 3).

I added a UIView with a CAGradientLayer on another UIView lie this:

public static void AddGradientView (CGColor color1, CGColor color2, UIView view) {
        UIView gradientView = new UIView (view.Bounds);
        gradientView.BackgroundColor = UIColor.Green;
        gradientView.AutoresizingMask = UIViewAutoresizing.All;

        CAGradientLayer gradient = new CAGradientLayer ();
        gradient.Frame = gradientView.Bounds;
        gradient.Colors = new CGColor[]{ color1, color2 };

        gradientView.Layer.InsertSublayer (gradient, 0);

        view.AddSubview (gradientView);
}

But the result is like this:

enter image description here

The problem is the gradient layer, His frame isn't fit to the wanted UIView. I think it's an Autolayout issues.

Can anyone put me some light on it?

Thanks in advance!

P.S The above code written in objective sharpie But it can be understood by an iOS developers easily ;)


Solution

  • CALayer and its subclasses are not affected by autolayout.

    To update a layers frame you can use viewDidLayoutSubviews if you are updating a from a view controller, or layoutSubviews from a custom UIView subclass.

    From a UIViewController:

    - (void)viewDidLayoutSubviews
    {
         [super viewDidLayoutSubviews];
         // you need to store a reference to the gradient layer and gradient views or fetch them from the sublayers and subviews
         self.gradient.frame = self.gradientView.bounds;
    }
    

    UIView subclass:

    - (void)layoutSubviews
    {
         [super layoutSubviews];
         self.gradient.frame = self.bounds;
    }