【问题标题】:UILabel Autolayout width troubleUILabel Autolayout 宽度问题
【发布时间】:2013-11-04 12:43:29
【问题描述】:

所以我正在尝试对单元格内容视图使用自动布局来获得正确的布局。所以我的问题是我有一个UILabel,它改变了它相对于它的文本的大小,我还有一个UIView 作为这个圆角标签的背景视图。所以我的问题是,如何强制这个UIView's 宽度比UILabel 宽10 个点。我设法使它的宽度相同,但我怎样才能让它总是变宽一定的长度?

提前谢谢你!

【问题讨论】:

  • UILabel的宽度加10点就行了
  • 但 UILabel 宽度会随着约束 Width >= 大于 100 像素而动态变化。那么我怎样才能在它的宽度上增加 10 个点呢?
  • 您可以通过编程方式添加它

标签: ios objective-c uiview autolayout nslayoutconstraint


【解决方案1】:
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:yourLabel
                                                                   attribute:NSLayoutAttributeWidth
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:yourLabel.superview
                                                                   attribute:NSLayoutAttributeWidth
                                                                  multiplier:1.0
                                                                    constant:10]; // <-- this
[yourLabel.superview addConstraint:widthConstraint];

【讨论】:

  • 完美解决了我的问题!
【解决方案2】:

自动布局约束只不过是形式的等式

attribute1 == multiplier × attribute2 + constant

请注意,以编程方式,您可以虚拟地对视图设置任何约束。然而,界面生成器有点受限,因为您只能关联某些 (attribute1,attribute2) 对,因为您已经注意到您可能无法提供 constant

看看 https://developer.apple.com/library/ios/DOCUMENTATION/AppKit/Reference/NSLayoutConstraint_Class/NSLayoutConstraint/NSLayoutConstraint.html

【讨论】:

  • 基本上你是对的,但是布局约束不限于relationEqual,如果你愿意将第二个属性绑定到一个常量上,你可以一起跳过第二个属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 2014-11-04
  • 2013-07-03
相关资源
最近更新 更多