【问题标题】:How to match labelwidth in scrollview with screenwidth with autolayout in ios如何将滚动视图中的标签宽度与ios中的自动布局匹配屏幕宽度
【发布时间】:2013-10-15 16:10:33
【问题描述】:

我最近开始在我的应用程序中使用自动布局并达到了一个点,我似乎找不到答案。

案例很简单:

我有一个 ViewController,里面有一个滚动视图。滚动视图应该在横向和纵向模式下占据所有空间。在这个滚动视图中,我想要一个标签,它需要足够的空间来显示其内容,但只能显示当前滚动视图宽度的最大值(不应超过屏幕大小)。剩下的文本应该被剪掉。

所以基本上我不希望滚动视图水平滚动。

如果可能,我更喜欢只使用界面生成器的解决方案。

【问题讨论】:

  • 您是否已经观看了 WWDC 2012 和 2013 的所有 Auto Layout 相关会议?
  • 我现在这样做了,我找到了一种处理它的方法,但代价是在标签上设置了固定宽度。这不是我想要的,但它可以完成工作

标签: iphone uiscrollview ios7 autolayout


【解决方案1】:

关于您的评论:这种情况会发生,因为滚动视图的大小取决于其内容(请参阅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 个点的距离(因为滚动视图将填满主视图)。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2015-08-26
    • 2015-12-03
    相关资源
    最近更新 更多