收集视图流布局未使用正确的像元宽度

时间:2019-06-03 22:19:16

标签: ios swift uicollectionview

我在下面有一个自定义UICollectionViewFlowLayout

class SnapCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        // Page width used for estimating and calculating paging.
        let pageWidth = self.itemSize.width + self.minimumLineSpacing

        // Make an estimation of the current page position.
        let approximatePage = self.collectionView!.contentOffset.x/pageWidth

        // Determine the current page based on velocity.
        let currentPage = (velocity.x < 0.0) ? floor(approximatePage) : ceil(approximatePage)

        // Create custom flickVelocity.
        let flickVelocity = velocity.x * 0.3

        // Check how many pages the user flicked, if <= 1 then flickedPages should return 0.
        let flickedPages = (abs(round(flickVelocity)) <= 1) ? 0 : round(flickVelocity)

        // Calculate newHorizontalOffset.
        let newHorizontalOffset = ((currentPage + flickedPages) * pageWidth) - self.collectionView!.contentInset.left

        return CGPoint(x: newHorizontalOffset, y: proposedContentOffset.y)
    }

}

但是,self.itemSize.width返回的是值50.0,而不是单元格的实际宽度。

我的收藏夹视图是水平的收藏夹视图,其中的单元格具有动态的宽度/高度(具体来说,它们是16:9的纵横比,因此取决于屏幕尺寸)。

如何使用正确的itemSize宽度反映单元格的实际宽度?

这是我的sizeForItemAt函数,来自集合视图类:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let imageWidth = UIScreen.main.bounds.width
    let imageHeight = imageWidth / (16 / 9)

    return CGSize(width: imageWidth, height: imageHeight)
}

0 个答案:

没有答案