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

J K*_*ney 12 uilabel ios 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];
Run Code Online (Sandbox Code Playgroud)

基本上,这些约束是为了执行小区,其中otherView在左边,aTextField是在权otherView在相同的Y电平,并且所述标记是下面aTextField和底部的右侧otherView.

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

sun*_*ppy 7

你需要

myLabel.adjustsFontSizeToFitWidth = YES;
myLabel.minimumScaleFactor = .5f;
Run Code Online (Sandbox Code Playgroud)

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

  • 感谢您的回复,但在实施此代码后,它仍然在顶部和底部被切断.我的字体大小为18.0f.我已经测试了字体,它需要的最小值是13.0f,所以我不明白为什么它不能自动缩小它直到达到0.5f乘数. (2认同)