具有AutoLayout的UICollectionView Cell + UiLabel

Att*_*a H 15 iphone ios autolayout uicollectionview uicollectionviewcell

我正在尝试将UILabel固定到它的父细胞上.我添加了四个约束(顶部,前导,尾随,底部),它们在iOS 8.0上运行良好,但在iOS 7.X上运行不正常.请看下面的图片:

[点击这里查看完整尺寸]

在此输入图像描述

我究竟做错了什么?请指教!

编辑#1

它似乎只是在Xcode 6 GM之后才被打破.我的方法在Xcode 6 beta 7中运行良好.

此外,如果我减少内部视图的宽度,它会抛出以下警告:

2014-09-10 19:58:28.109 Test[57827:60b] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x799573a0 H:|-(8)-[UIView:0x798a86e0]   (Names: '|':UIView:0x798ae5d0 )>",
    "<NSLayoutConstraint:0x799573d0 H:[UIView:0x798a86e0]-(43)-|   (Names: '|':UIView:0x798ae5d0 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x798a8b00 h=--& v=--& H:[UIView:0x798ae5d0(50)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x799573d0 H:[UIView:0x798a86e0]-(43)-|   (Names: '|':UIView:0x798ae5d0 )>

Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
Run Code Online (Sandbox Code Playgroud)

Att*_*a H 21

覆盖自定义单元格layoutSubviews是一种可能的解决方法:

override func layoutSubviews() {
    contentView.frame = bounds
    super.layoutSubviews()
}
Run Code Online (Sandbox Code Playgroud)

  • 哇,神奇地删除了我的幽灵约束:`<NSAutoresizingMaskLayoutConstraint:0x7fb942895a20 h = - &v = - &H:[UIView:0x7fb942891cf0(50)]>`.你能解释一下这是怎么解决的吗?假设这是因为单元格的contentView带有默认边距(距其外观为8px),我是否正确? (2认同)

coc*_*oco 6

UIView:0x798ae5d0是CollectionViewCell的contentView.不知何故,它在某个时刻使用UICollectionViewCells defaultSize,即(50.0,50.0).

<NSAutoresizingMaskLayoutConstraint:0x798a8b00 h=--& v=--& H:[UIView:0x798ae5d0(50)]>
Run Code Online (Sandbox Code Playgroud)

由于水平边距8 + 43 = 51大于contentView(50),因此无法满足布局.

<NSLayoutConstraint:0x799573a0 H:|-(8)-[UIView:0x798a86e0]   (Names: '|':UIView:0x798ae5d0 )>
<NSLayoutConstraint:0x799573d0 H:[UIView:0x798a86e0]-(43)-|  (Names: '|':UIView:0x798ae5d0 )>
Run Code Online (Sandbox Code Playgroud)

可以使布局更灵活,因此它也适用于(50.0,50.0)尺寸.在您的情况下,通过将等于43更改为<= 43或通过将优先级降低到1000到750或999.


Vil*_*urz 5

问题在于您的自定义视图(UILabel)具有约束,该约束与单元格(或更好的单元格的contentView)约束冲突。单元格的NSAutoresizingMaskLayoutConstraint是根据您在xib(或情节提要)的UICollectionView属性中设置的单元格大小自动创建的。我已经通过显式设置解决了类似的问题(*)

- (void)awakeFromNib {

    [super awakeFromNib];

    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
}
Run Code Online (Sandbox Code Playgroud)

在我的自定义UICollectionViewCell子类中。这摆脱了在情节提要中设置的像元大小约束。

(*)免责声明:我的collectionView具有根据其内容视图自动调整大小的单元格,该视图由自动布局定义。我收到有关内容自动布局的约束冲突以及Storyboard中显式大小的警告。这帮助我摆脱了这些警告。