UILabel文本不会使用自动布局自动resize

我试图实现一个受约束的UITableViewCell子类,除了UILabel之外,一切工作都很完美。 我设置的限制条件肯定会被强制执行,但是当约束冲突时,标签内部的文本不会调整为较小的字体大小。 相反,UILabel的高度被截断,字体保持不变,这意味着字母在顶部和底部被切断。

有什么方法我必须打电话才能使这个工作? 我会认为自动布局将足够聪明,自动调整字体大小,所以我有点失落,为什么发生这种情况。

相关编码:

 self.label = [[UILabel alloc] initWithFrame:CGRectZero]; self.label.textColor = [UIColor whiteColor]; self.label.translatesAutoresizingMaskIntoConstraints = NO; self.label.textAlignment = NSTextAlignmentCenter; self.label.numberOfLines = 1; [self.contentView addSubview:self.label]; NSLayoutConstraint *otherViewToLabelHorizontalConstraint = // Make sure that the label is always to the right of the other view. [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:self.otherView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]; NSLayoutConstraint *aTextFieldToLabelVerticalConstraint = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:self.aTextField attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]; 

基本上,这些约束是为了执行一个单元格,其中otherView位于左侧, aTextField位于aTextField的右侧,位于相同的y级别,而标签位于aTextField下方, otherView底部的otherView

像往常一样,感谢您的帮助。

你需要

 myLabel.adjustsFontSizeToFitWidth = YES; myLabel.minimumScaleFactor = .5f; 

然后标签字体大小将自动调整。

随着adjustsFontSizeToFitWidthminimumScaleFactor的设置,您还需要将标签的内容压缩设置为低优先级。 看看这个objc.io文章的“压缩阻力和内容拥抱”部分。 基本上,如果您的标签具有比尾随约束更低的压缩阻力优先级,则应该调整标签大小:

 [myLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal]; 

我通过设置所需的宽度约束来解决这个问题,我把标签链接到视图。

  NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:width]; 

并确保此约束的优先级设置为UILayoutPriorityRequired。

 [constraint setPriority:UILayoutPriorityRequired]; 

文本正在调整标签到超视图,而不是文本字段的大小,所以我推断必须有与标签的最终宽度的布局计算中涉及的元素的固有尺寸的问题。