ios - 应用转换 : Assertion failure in -[layoutSublayersOfLayer:] 时自动布局崩溃

标签 ios objective-c autolayout transformation

我有一个自定义 View ,它在右下角显示一个 UILabel。 View 是在从 initWithCoder:initWithFrame: 调用的方法中设置的,如下所示:

MCLabel* likesLabel = [[MCLabel alloc] init];
likesLabel.mc_textPadding = UIEdgeInsetsMake(0, 10, 0, 10);
likesLabel.font = [UIFont fontWithName:@"FontAwesome" size:12.f];
[likesLabel setText:@"test"];
likesLabel.numberOfLines = 2;
likesLabel.backgroundColor = [UIColor colorWithWhite:1 alpha:.8];
likesLabel.textColor = UIColor.blackColor;
likesLabel.translatesAutoresizingMaskIntoConstraints = NO;
likesLabel.textAlignment = NSTextAlignmentCenter;
likesLabel.mc_verticalTextAlignment = MCVerticalTextAlignmentTop;

[self addSubview:likesLabel];
self.likesLabel = likesLabel;

NSLayoutConstraint* widthConstraint = [NSLayoutConstraint constraintWithItem:likesLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1 constant:1];
NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:likesLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:likesLabel attribute:NSLayoutAttributeWidth multiplier:2/5.f constant:1];
NSLayoutConstraint* horizontalPosition  = [NSLayoutConstraint constraintWithItem:likesLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1 constant:1];
NSLayoutConstraint* verticalPosition  = [NSLayoutConstraint constraintWithItem:likesLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:1];
[likesLabel addConstraints:@[heightConstraint]];
[self addConstraints:@[widthConstraint, horizontalPosition, verticalPosition]];

现在,如果我像这样保留所有内容,我不会有任何问题,但是,一旦我将转换应用于此标签(这是 UILabel 的子类,如果重要的话,只需添加垂直对齐和边缘插入)应用程序因控制台错误而崩溃:

*** Assertion failure in -[MCView layoutSublayersOfLayer:], /SourceCache/UIKit/UIKit-2935.138/UIView.m:8794
Auto Layout still required after executing -layoutSubviews

断言暗示子类在覆盖方法时可能没有调用 [super layoutSubviews] 但我调用了。

由于很明显这里的问题是自动布局设置,我担心我忽略了某些东西,布局可能不明确,因此崩溃。

请注意:如果我在 - (void)didMoveToSuperview 方法中移动转换,相同的代码不会在 iOS 8 上崩溃。

有人可以帮忙吗?

最佳答案

由于在 viewWillLayoutSubviews 中进行约束调整,我在 iOS7(但不是 iOS8)中遇到了这个问题。将约束调整移动到 viewWillAppear 为我修复了它。

关于ios - 应用转换 : Assertion failure in -[layoutSublayersOfLayer:] 时自动布局崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24549334/

相关文章:

ios - 动态表格 View 单元格,防止创建自动高度约束

ios - 在导航栏中隐藏和显示后退按钮

ios - NSDecimal 等于 NSDecimalNumber 值?

ios - 引用 Objective-C 代码构建 Swift 框架

ios - 解析json数据图像到 ImageView

ios - 自动布局两个相同大小的容器

ios - iPhone SE 和 4s 的 Xcode 安全区域故障

swift - 标签高度不会动态变化

ios - 将手势识别器添加到 SKShapeNode Swift 4

ios - UIScrollView 中的 UItextfield 并用放大镜移动光标