【问题标题】:UICollectionview cell with dynamic height and half width具有动态高度和半宽的 UICollectionview 单元格
【发布时间】:2020-03-08 04:40:40
【问题描述】:

我正在尝试根据给定的文本创建具有半宽和动态高度的集合视图 (Expected View)。

我正在尝试通过(ViewController 中的代码)实现这一目标

    let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    flowLayout.estimatedItemSize = CGSize(width: (UIScreen.main.bounds.width / 2), height: 2000.0)
    flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize

And(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 
}

通过使用上面的代码,我可以实现创建collectionviewActual view(半宽和动态高度)。但集合视图单元格高度不等于相邻。实际上,此集合视图单元格高度应与相邻单元格高度(具有最大高度)相同。如何根据相邻单元格大小更新单元格大小?

提前致谢

【问题讨论】:

  • 为什么要设置 UICollectionViewFlowLayout.automaticSize,评论这行试试看
  • 这一行就够了 flowLayout.estimatedItemSize = CGSize(width: (UIScreen.main.bounds.width / 2), height: 2000.0)
  • @YagneshDobariya:不走运。
  • 你能解决这个问题吗?

标签: ios swift collectionview


【解决方案1】:

使用 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 )
}

【讨论】:

  • 上面的代码使collectionview中的所有单元格高度为2000。这里不是这样。
  • 您可以根据特定项目中的文本更改高度,就像我们在聊天视图中所做的那样,这可能会有所帮助stackoverflow.com/questions/446405/…
【解决方案2】:

将此代码添加到您的 CollectionViewCell 类中:

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
}

【讨论】:

  • 我也试过了,但是单元格大小没有按预期更新。
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
相关资源
最近更新 更多