【问题标题】:How do I expand a custom collection view cell that has a table view on it?如何展开具有表格视图的自定义集合视图单元格?
【发布时间】:2019-07-29 22:32:03
【问题描述】:

我正在尝试自动使 collectionView 单元格垂直扩展以显示单元格上的 tableView。

tableView 已正确填充,我在设置 cell.tableView.isHidden = false 后在集合视图单元格上调用 reload

Swift 4.2、Xcode 10.3

编辑:为了澄清我的问题,当我在单元格上显示/隐藏 tableView 时,我试图切换展开/折叠单元格(自动调整大小)。

collectionView flowLayout 变量:

// FlowLayout of the collectionView 
var flowLayout: UICollectionViewFlowLayout {
        return self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
}

collectionView viewDidLoad():

self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize

collectionView 单元格:

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

        let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)

        // Specify you want _full width_
        let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0)

        // Calculate the size (height) using Auto Layout
        let autoLayoutSize = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultLow)
        let autoLayoutFrame = CGRect(origin: autoLayoutAttributes.frame.origin, size: autoLayoutSize)

        // Assign the new size to the layout attributes
        autoLayoutAttributes.frame = autoLayoutFrame
        return autoLayoutAttributes
}

点击“显示表格视图”按钮时的collectionView单元格:

cell.tableView.isHidden = false
collectionView.reloadItems(at: [indexPath])

谢谢。

【问题讨论】:

  • 我在这里看不到任何问题,您可以正确填充 UICollectionViewCell,这不是您想要的吗?
  • 感谢您的回复,我在原始帖子中添加了一些清晰度:为了澄清我的问题,我试图在显示/隐藏时切换展开/折叠单元格(自动调整大小)单元格上的 tableView。

标签: ios swift uicollectionview


【解决方案1】:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {


let cell = collectionView.cellForItem(at: indexPath) as! yourCell

if cell.tableView.isHidden { 

return CGize(width: cellWidth, height:0)

  } 

    return  CGSize(width: tableViewWidth, height: TotalTableViewCellsHeight)     



}

或者

 @IBAction func showTableView(_ sender: Any) {

 flowLayout.itemSize = CGSize(width: newCellWidth, height: newCellHeight)

   }

【讨论】: