UILabel文本不会使用“自动布局”自动调整大小

时间:2013-06-17 22:15:41

标签: ios uilabel autolayout nslayoutconstraint

我正在尝试实现受约束的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位于同一y级otherView的右侧,标签为低于aTextField以及otherView底部的右侧。

像往常一样,感谢您对此的任何帮助。

3 个答案:

答案 0 :(得分:7)

你需要

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

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

答案 1 :(得分:2)

除了adjustsFontSizeToFitWidthminimumScaleFactor的设置外,您还需要将标签的内容压缩设置为具有低优先级。查看此objc.io essay的“抗压缩和内容拥抱”部分。基本上,如果您的标签的抗压缩优先级低于尾随约束,则标签应调整大小:

[myLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow
                                 forAxis:UILayoutConstraintAxisHorizontal];

答案 2 :(得分:2)

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

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

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

[constraint setPriority:UILayoutPriorityRequired];

当将标签固定到超视图而不是文本字段时,文本正在调整大小,因此我推断出标签最终宽度的布局计算中涉及的元素的固有大小一定存在问题。