Collection View Cell 子视图框架在单元格被重用之前不可用

Collection View Cell subview frame not available until cell is reused

我有一个包含子视图的集合视图单元格,我正在尝试获取与父视图相关的框架。

到目前为止,我已经成功获取了子视图的框架,但是对于前 x 个 visible 单元格,返回的框架总是 (0,0 ,0,0).

在我将它们滚动出视图并滚动回到那些 x 单元格后,返回的帧很好,并且子视图的帧计算正确。

有什么想法吗?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let window = UIApplication.shared.keyWindow

    let selectedCell = self.collectionView(self.cellCollectionView, cellForItemAt: indexPath) as! postCell

    let photoItem = selectedCell.photo
    let photoItemPosition = photoItem.frame

    let convertedFrame = selectedCell.convert(photoItemPosition, to: window)

    print(photoItemPosition)
    print(convertedFrame)
}

您必须在 layoutSubviews 中更新 photo 实例的框架。 覆盖 collectionView 单元格中的 layoutSubviews class

override func layoutSubviews ()
{
    super.layoutSubviews()
    //Set the self.photo frame 
}