如何增加UICollectionViewCell的高度并保持在ScrollView中的相同位置?

时间:2016-08-14 21:00:48

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

在我的应用程序中,我有一个UICollectionViewController,我更改了UICollectionViewLayout。自定义UICollectionViewFlowLayout只会更改单元格的高度。问题是在设置新UICollectionViewFlowLayout时,UICollectionView中的位置会完全改变,尤其是我的位置越来越低。我的目标是在更新UICollectionViewCell之后,让位于顶部的UICollectionViewLayout(但未被导航栏隐藏,甚至更高)隐藏在视图的顶部。

以下是我试图解决的一些代码:

class PacksCollectionViewLayout: UICollectionViewFlowLayout {

    convenience init(height: CGFloat) {
        self.init()
        itemSize = CGSize(width: 80, height: height)
        minimumInteritemSpacing = 10
        minimumLineSpacing = 10
        sectionInset.left = 10
        sectionInset.right = 10
        scrollDirection = .vertical
    }

    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
        return collectionView!.contentOffset
    }
}

class PacksCollectionViewController: UICollectionViewController {

    var largeCells = false {

        let height:CGFloat = largeCells ? 110 : 80
        var lowestIndexPath:IndexPath? {
            return self.collectionView?.indexPathsForVisibleItems.min()
        }

        UIView.animate(withDuration: 0.3){
            self.collectionView?.collectionViewLayout.invalidateLayout()
            self.collectionView?.setCollectionViewLayout(PacksCollectionViewLayout(height: height), animated: true)
            if let index = lowestIndexPath{
                self.collectionView?.scrollToItem(at: index, at: .top, animated: false)
            }
        }
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: PacksCollectionViewCell.identifier, for: indexPath)
    }
}

当您尝试滚动到列为UICollectionViewCell中最低IndexPath的{​​{1}}时,它会向远处移动,因为这些单元格显然仍然可见。有关此事的任何解决方案吗?

1 个答案:

答案 0 :(得分:0)

这就是我做的方式,我希望如果不这样做会有所帮助和抱歉 所以在您的流程布局中添加此代码

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

override init() {
    super.init()
    commonInit()
}

func commonInit() {
    minimumLineSpacing = 10.0
}

fun yourCollectionView(collectionView: UICollectionView, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: 230.0)
}

并在您的主集合控制器上添加此

  let layout = yourFlowLayout()



   override func viewDidLoad() {
    super.viewDidLoad()

 collectionView?.collectionViewLayout = layout


 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return layout.yourCollectionView(collectionView, sizeForItemAtIndexPath: indexPath)
}

我希望这有助于:)