【发布时间】:2015-04-24 14:37:38
【问题描述】:
我一直在玩弄动态 UICollectionViewCell,并注意到在 iOS 8 上,在 UICollectionViewCell 上调用 cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) 返回的宽度不正确。目前,解决此问题的唯一解决方法是显式添加宽度约束以强制单元格的宽度。以下代码用于 Cell 子类:
func calculatePreferredHeightForFrame(frame: CGRect) -> CGFloat {
var newFrame = frame
self.frame = newFrame
let widthConstraint = NSLayoutConstraint(item: contentView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: CGRectGetWidth(frame))
contentView.addConstraint(widthConstraint)
self.setNeedsUpdateConstraints()
self.updateConstraintsIfNeeded()
self.setNeedsLayout()
self.layoutIfNeeded()
let desiredHeight: CGFloat = self.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
newFrame.size.height = CGFloat(ceilf(Float(desiredHeight)))
contentView.removeConstraint(widthConstraint)
return CGRectGetHeight(newFrame)
}
我知道在 iOS 8 和动态 UICollectionViewFlowLayout 中,UICollectionViewCell 的 contentView 以不同方式处理约束,但是我在这里缺少什么吗?需要做什么来确保 systemLayoutSizeFittingSize 在单元格上使用特定宽度?
我也看到了这篇文章 (Specifying one Dimension of Cells in UICollectionView using Auto Layout),并相信这实际上可能会使我的问题无效。也许 UICollectionViewFlowLayout 不是为只有一个动态维度的单元格设计的,但这仍然不能解释为什么单元格会给出不寻常的宽度。
【问题讨论】:
-
我有完全相同的问题,我的单元格宽度总是返回为 320(xib 视图大小)。无法真正解决它...
-
这个单元格中有多行 UILabel 吗?如果是这样,您可能有错误的首选最大布局宽度。
-
@hris.to 如果您再次阅读该问题,您会发现它与标签无关,而是与整个单元格的大小有关
-
@DanielGalasko 确定我明白这一点。几天前 UITableViewCell 就发生在我身上。如果将preferedMaxLayoutWidth 设置为240px,它将像一个约束一样,当收到systemLayoutSizeFittingSize 时,它会返回比实际帧宽度更大的宽度。您必须继承标签并覆盖 setBounds 以根据新标签宽度更新 preferredMaxLayoutWidth(仅在值不同时更新它,并且在 super setBounds 调用之后)。
-
如果您在实施此解决方案时遇到问题,请告诉我,所以我会留下完整解决方案的答案。
标签: ios xcode6 autolayout uicollectionview