ios - 自动布局不传递给子层

标签 ios iphone autolayout calayer cagradientlayer

我正在为 iOS v5.8.3(build 3)使用 Xamarin

我在另一个 UIView 上添加了一个带有 CAGradientLayerUIView 是这样的:

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);
}

但是结果是这样的:

enter image description here

问题是渐变层,他的 frame 不适合想要的 UIView。 我认为这是一个 Autolayout 问题。

谁能给我一些启发?

提前致谢!

附言 上面的代码是用 objective sharpie 写的,但是 iOS 开发者很容易理解 ;)

最佳答案

CALayer 及其子类不受自动布局的影响。

要更新图层框架,您可以使用 viewDidLayoutSubviews(如果您从 View Controller 更新 a),或者从自定义 UIView 子类更新 layoutSubviews

来自 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 子类:

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

关于ios - 自动布局不传递给子层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29644384/

相关文章:

ios - 调试 Alamofire 请求

ios - iOS 上单页的 Flutter 设备方向

iOS Storyboard 有条件地显示 View

iphone - 尝试使用 CAAnimationGroup 放大和缩小 UIButton 时出现问题

ios - 当 `translatesAutoresizingMaskIntoConstraints` 设置 `NO` 时 View 消失

ios - 保存 UISwitch 结果和 NSUserDefaults

iphone - 在 Google Places API 中嵌入当前位置(经度和纬度)

ios - 将音频修剪为视频长度

ios - 是否可以通过自动布局实现重叠 View ?

ios - Swift 4 NSLayoutConstraint 无法正常工作