[英]UICollectionview cell with dynamic height and half width
Im trying to create collection view ( Expected View ) with half width and dynamic height based on given text.我试图根据给定的文本创建具有半宽和动态高度的集合视图(预期视图)。
I am trying to achieve this by (Code in ViewController)我正在尝试通过(ViewController 中的代码)来实现这一点
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.estimatedItemSize = CGSize(width: (UIScreen.main.bounds.width / 2), height: 2000.0)
flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
And (Code in UICollectionviewCell)和(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
}
By using the above code, I can achieve to create collectionview Actual view (half width and dynamic height).通过使用上面的代码,我可以实现创建collectionview的实际视图(半宽和动态高度)。 But collection view cell height not equal to the adjacent.
但集合视图单元格高度不等于相邻。 Actually this collection view cell height should be same as adjacent cell height(which is having the maximum height).
实际上,此集合视图单元格高度应与相邻单元格高度(具有最大高度)相同。 How to update the cell size based on the adjacent cell size?
如何根据相邻单元格大小更新单元格大小?
Thanks in advance提前致谢
Use UICollectionViewDelegateFlowLayout使用 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 )
}
Add this code in your CollectionViewCell class:在您的 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.