微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

滚动后collectionview项不会在中心

如何解决滚动后collectionview项不会在中心

我现在正在为图片制作一个 collectionView,我想让它像下面这样。

然而,当我向右/向左滚动时,下一个项目永远不会在中心,我尝试了很多方法仍然无法解决问题。 有人可以帮我吗?

enter image description here

enter image description here

下面是代码

func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,insetForSectionAt section: Int) -> UIEdgeInsets {
        let cellCount = CGFloat(Config.banners.count)

        if cellCount > 0 {
            let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
            let cellWidth = screenSize.width - flowLayout.minimumInteritemSpacing
            flowLayout.itemSize = CGSize(width: cellWidth,height: 250)
            flowLayout.minimumLinespacing = -60
            let totalCellWidth = cellWidth*cellCount
            let totalSpacingWidth = 30 * (cellCount - 1) 
            let contentWidth = collectionView.frame.size.width
            
            if (totalCellWidth < contentWidth) {
                print("totalCellWidth < contentWidth")
                let padding = (contentWidth - totalCellWidth) / 2.0
                return UIEdgeInsets(top: 0,left: padding,bottom: 0,right: padding)
            } else {
                print("totalCellWidth > contentWidth")
                return UIEdgeInsets(top: 0,left: 10,right: 0)
            }
        }
        return UIEdgeInsets.zero
    }

解决方法

在您的代码中添加这些行 collectionviewflowdelegate 方法。它会起作用。我通过添加这些方法实现了同样的目的。

func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width  = UIScreen.main.bounds.width / 3.0
    let height = collectionView.frame.size.height
    return CGSize(width: width,height: height)
}


func collectionView(_ collectionView: UICollectionView,minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView,minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。