旋转时无法缩小UILabel以适应内容

时间:2014-02-23 17:17:30

标签: ios uilabel autolayout autoresize

我无法使用自动布局让我的UILabel正确调整大小。基本上我希望我的标签总是大小足以匹配其内容。这里有一些图片来证明我的意思。

enter image description here

enter image description here

注意横向位置的额外顶部和底部填充。我不希望这样。我希望标签垂直收缩,以便它只包含其内容。

顶部布局指南的顶部约束为33,超级视图的前导约束为75,超级视图的尾随约束为75.

所以我的目标是再次允许根据方向调整标签大小,但是标签只包含其内容而不进行任何填充。

感谢。

3 个答案:

答案 0 :(得分:2)

您需要的是灵活的约束。因此,假设底部约束为大于或等于0 ,并将其优先级设置为 100 。然后选择UILabel并将其垂直内容拥抱优先级更改为 99 。这样,内容拥抱优先于底部距离,填充将在所有方向上消失。

答案 1 :(得分:2)

看起来只更新了对任何更改(旋转,xib调整大小等)的preferredMaxLayoutWidth,它会影响大小。

实施例: 我在IB中设计了一个带有iPhone屏幕尺寸的视图:

iPhone Portrait

要使其在横向上工作,请在视图控制器中添加以下代码:

- (void)updateLabelPreferredMaxLayoutWidthToCurrentWidth:(UILabel *)label
{
    label.preferredMaxLayoutWidth =[label bounds].size.width;
}

-(void)updateLabels
{
    [self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label1];
    [self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label2];
    [self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label3];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

    [self updateLabels];
}

基本上我们只是在willAnimateRotationToInterfaceOrientation中更改每个标签的preferredMaxLayoutWidth,因为那里的大小正在改变。结果是:

iPhone Landscape

如果您想支持多种显示尺寸,只需在viewDidAppear中调用updateLabels,如下所示:

-(void)viewDidAppear:(BOOL)animated
{
    [self updateLabels];
}

这是因为我设计了一个带有iPhone显示尺寸的单个xib,但是想要支持多种显示尺寸。视图已经出现后,计算所有元素的确切大小。

iPad Portrait Demo在viewDidAppear中使用相同的xib和调整代码:

iPad Portrait Demo

希望这有帮助。

答案 2 :(得分:1)

编辑:这是一个比我的更好的答案:https://stackoverflow.com/a/15927392/3414722
它应该完全符合您的要求,并且可以与自动布局一起使用。


每次更改方向时,您都可以在标签上调用sizeToFit。理论上,sizeToFit不应该与自动布局一起使用,但它应该为您提供所需的效果。以下是您在视图中需要的代码:

- (void)updateViewConstraints {
    [super updateViewConstraints];

    [self.label sizeToFit];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

    [self.view setNeedsUpdateConstraints];
}
相关问题