如何将滚动视图中的标签宽度与屏幕宽度匹配,并在ios中使用自动布局

时间:2013-10-08 16:03:10

标签: iphone uiscrollview ios7 autolayout

我最近开始在我的应用中使用autolayout并达到了一个点,我似乎找不到答案。

案件很简单:

我有一个ViewController,里面有一个scrollview。 scrollview应占用横向和纵向模式中的所有空间。在这个滚动视图中,我希望有一个标签,它占用足够的空间来显示其内容,但仅限于当前scrollview-width的最大值(应该不超过屏幕大小)。剩下的文字应该被剪掉。

所以基本上我不想让scrollview水平滚动。

如果可能,我更喜欢仅使用界面构建器的解决方案。

1 个答案:

答案 0 :(得分:0)

关于你的评论:这种情况发生了,因为滚动视图的大小取决于其内容(参见Pure Auto Layout Approach部分)。因此,标签的大小不能取决于滚动视图的大小。

有一种解决方法 - 您可以在标签和主视图之间设置约束,例如:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.label
                                                      attribute:NSLayoutAttributeLeft
                                                      relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeLeft
                                                     multiplier:1.0
                                                       constant:40]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.label
                                                      attribute:NSLayoutAttributeRight
                                                      relatedBy:NSLayoutRelationLessThanOrEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeRight
                                                     multiplier:1.0
                                                       constant:-40]];

使用这种方法,标签的左(右)侧与滚动视图的左(右)侧之间至少有40个点的距离(因为滚动视图将填充主视图)。 / p>

或者,您可以在标签和主视图的width之间设置约束。它是这样的:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.label
                                                      attribute:NSLayoutAttributeWidth
                                                      relatedBy:NSLayoutRelationLessThanOrEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeWidth
                                                     multiplier:1.0
                                                       constant:-40]];

所以现在标签的宽度不会大于主视图的width - 40