两个标签对齐及其约束

时间:2017-04-03 14:17:08

标签: ios objective-c swift constraints

我有2个标签:描述标签(带红色背景)和结果标签(灰色文字)

如何为此示例设置约束,以使结果标签具有其内容的大小和描述标签,直到结果leadingAnchor? (就像我在第二排)

example

目标C

[self.customTextLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.counterLabel.leadingAnchor].active = YES;
[self.counterLabel.widthAnchor constraintGreaterThanOrEqualToConstant:0].active = YES;

迅速

titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: counterLabel.leadingAnchor).isActive = true
counterLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 0).isActive = true

我有一个解决方案,我觉得它很难看。

self.counterLabelWidthConstraint = [self.counterLabel.widthAnchor constraintEqualToConstant:0];
self.counterLabelWidthConstraint.active = YES;

然后在我设置文本后:

self.counterLabelWidthConstraint.constant = [self.counterLabel sizeThatFits:CGSizeMake(CGFLOAT_MAX, self.counterLabel.height)].width;

4 个答案:

答案 0 :(得分:3)

使用自动布局执行此操作的方法是使用2个标签中的contentCompressionResistancePriority。将第一个标签的pririty设置为NSLayoutPriorityRequired,为第一个标签设置较低的NSLayoutPriorityDefaultLow。然后,只要2个标签有适当的约束将它们锚定到它们的超视图和彼此,第一个标签应该压缩而第二个标签不应该压缩。

答案 1 :(得分:2)

您只需要将右侧/灰色标签的水平抗压强度增加到高于左侧/红色标签的水平抗压性。这告诉视觉布局,如果两个标签没有足够的空间,左边的那个将在缩小右边的标签之前被压缩。 750是所有视图的默认值,因此只需将右侧/灰色标签的水平压缩阻力增加到751,您就应该好了。

enter image description here

答案 2 :(得分:0)

快速5

<#label#>.setContentCompressionResistancePriority(.required, for: .horizontal)

具有此属性的标签不会水平压缩。

答案 3 :(得分:-1)

您可以在故事板中设置约束。选择标签1(红色背景)和标签的超视图集宽度是相等的约束。选择标签1并双击其宽度约束,从结果窗口中,您可以看到Lable 1宽度等于superview,值常量为“1”。将“1”更改为0.7或您想要的百分比。

相关问题