[英]UICollectionview cell with dynamic height and half width
我试图根据给定的文本创建具有半宽和动态高度的集合视图(预期视图)。
我正在尝试通过(ViewController 中的代码)来实现这一点
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.estimatedItemSize = CGSize(width: (UIScreen.main.bounds.width / 2), height: 2000.0)
flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
和(UICollectionviewCell 中的代码)
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var frame = layoutAttributes.frame
frame.size.height = ceil(size.height)
layoutAttributes.frame = frame
return layoutAttributes
}
通过使用上面的代码,我可以实现创建collectionview的实际视图(半宽和动态高度)。 但集合视图单元格高度不等于相邻。 实际上,此集合视图单元格高度应与相邻单元格高度(具有最大高度)相同。 如何根据相邻单元格大小更新单元格大小?
提前致谢
使用 UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath:
IndexPath) -> CGSize
{
//let padding: CGFloat = 5
let collectionViewSize = collectionView.frame.size.width / 2
return CGSize(width: collectionViewSize , height: 2000 )
}
在您的 CollectionViewCell class 中添加此代码:
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
newFrame.size.height = ceil(size.height)
newFrame.size.width = UIScreen.main.bounds.width / 2
layoutAttributes.frame = newFrame
return layoutAttributes
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.