iOS-UICollectionView动态高度

时间:2018-12-14 08:24:31

标签: ios uicollectionview uicollectionviewflowlayout

我的流程布局定义如下

internal lazy var layout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 16
    layout.sectionInset = UIEdgeInsets(top: layout.minimumLineSpacing, left: layout.minimumLineSpacing , bottom: layout.minimumLineSpacing , right: layout.minimumLineSpacing )
    layout.estimatedItemSize = CGSize(width: UIScreen.main.bounds.size.width - (layout.sectionInset.left + layout.sectionInset.right), height: 10)
    return layout
}()

然后在单元格中设置期望内容的高度

override open func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    setNeedsLayout()
    layoutIfNeeded()
    let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
    var newFrame = layoutAttributes.frame
    newFrame.size.height = ceil(size.height)
    layoutAttributes.frame = newFrame
    return layoutAttributes
}

它有效。我得到的单元格达到了我期望的高度,但是控制台中每个单元格都会出现一个讨厌的警告

[LayoutConstraints] 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. 
(
    "<NSLayoutConstraint:0x600003c1e490 V:|-(0)-[UIView:0x7fdc8bead5d0]   (active, names: '|':VLCContentCollectionViewCell:0x7fdc8becf8e0 )>",
    "<NSLayoutConstraint:0x600003c1ec60 V:[UIView:0x7fdc8bead5d0]-(0)-|   (active, names: '|':VLCContentCollectionViewCell:0x7fdc8becf8e0 )>",
    "<NSLayoutConstraint:0x600003c4bb60 V:|-(0)-[VLAsyncImageView:0x7fdc8bea20a0]   (active, names: '|':UIView:0x7fdc8bead5d0 )>",
    "<NSLayoutConstraint:0x600003c43070 V:[VLAsyncImageView:0x7fdc8bea20a0]-(0)-|   (active, names: '|':UIView:0x7fdc8bead5d0 )>",
    "<NSLayoutConstraint:0x600003c5f340 VLAsyncImageView:0x7fdc8bea20a0.height == 100   (active)>",
    "<NSLayoutConstraint:0x600003f8cb90 'UIView-Encapsulated-Layout-Height' VLCContentCollectionViewCell:0x7fdc8becf8e0.height == 10   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600003c5f340 VLAsyncImageView:0x7fdc8bea20a0.height == 100   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

我非常确定这是因为约束'UIView-Encapsulated-Layout-Height'保存了流布局的预期项目大小的值,因为如果我将其设置为100,则不会显示日志消息。 但是,我正在寻找动态像元高度,因此即使将其设置为100,它也会在其他位置失败。

所以我的问题是在定义动态单元格时是否做错了什么?还是有一种方法可以降低估算的像元高度的优先级,以防万一,可以制止这种约束?

0 个答案:

没有答案