gpt4 book ai didi

swift - 设置 UICollectionView 的 UIEdgeInsets

转载 作者:行者123 更新时间:2023-11-30 12:38:16 24 4
gpt4 key购买 nike

我希望 UICollectionView 的项目位于中心,因此我编写了以下代码:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let collectionViewWidth = collectionView.bounds.width
let collectionViewHeight = collectionView.bounds.height
let numberOfRows = CGFloat(collectionView.numberOfItemsInSection(0))
let leftValue = (collectionViewWidth / 2.0) - (numberOfRows * 5) - (numberOfRows * (collectionViewHeight / 2.0))
print(leftValue)
return UIEdgeInsets(top: 0, left: leftValue, bottom: 0, right: 0)
}

但现在的问题是我无法将其滚动到左侧,因为我的左侧插图发生了变化,请建议我任何解决方案。

最佳答案

我通过一些计算等得出了这个结论,所以这里是代码:

func refreshCollectionView(count: Int) {
let collectionViewHeight = collectionView.bounds.height
let collectionViewWidth = collectionView.bounds.width
let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth / collectionViewHeight)
if numberOfItemsThatCanInCollectionView > count {
let totalCellWidth = collectionViewHeight * CGFloat(count)
let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1)
// leftInset, rightInset are the global variables which I am passing to the below function
leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
rightInset = -leftInset
} else {
leftInset = 0.0
rightInset = -collectionViewHeight
}
collectionView.reloadData()
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}

更详细的代码你可以在这里查看我的代码 https://github.com/anirudha-music/CollectionViewCenter

关于swift - 设置 UICollectionView 的 UIEdgeInsets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42596046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com