gpt4 book ai didi

ios - 如何在 Swift3.0 中居中对齐 UICollectionView 的单元格?

转载 作者:IT王子 更新时间:2023-10-29 05:32:24 24 4
gpt4 key购买 nike

描述:

Objective-CSwift2.0 的答案:How to center align the cells of a UICollectionView?

我通常会尝试将 Swift2.0 答案转换为 Swift3.0 解决方案,但是方法:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2
return UIEdgeInsetsMake(0, edgeInsets, 0, 0);
}

Swift3.0 中似乎不存在,我发现唯一有用的其他方法是:

func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
<#code#>
}

但我不确定如何正确实现它。

问题:

如何在 Swift3.0 中居中对齐 UICollectionView 的单元格?

(适用于 iOS 和 tvOS 的简单通用解决方案将是完美的)

最佳答案

这最终成为我使用的解决方案。阅读代码注释以获得更好的理解。 swift 5

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

//Where elements_count is the count of all your items in that
//Collection view...
let cellCount = CGFloat(elements_count)

//If the cell count is zero, there is no point in calculating anything.
if cellCount > 0 {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing

//20.00 was just extra spacing I wanted to add to my cell.
let totalCellWidth = cellWidth*cellCount + 20.00 * (cellCount-1)
let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right

if (totalCellWidth < contentWidth) {
//If the number of cells that exists take up less room than the
//collection view width... then there is an actual point to centering them.

//Calculate the right amount of padding to center the cells.
let padding = (contentWidth - totalCellWidth) / 2.0
return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
} else {
//Pretty much if the number of cells that exist take up
//more room than the actual collectionView width, there is no
// point in trying to center them. So we leave the default behavior.
return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
}
}
return UIEdgeInsets.zero
}

关于ios - 如何在 Swift3.0 中居中对齐 UICollectionView 的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585822/

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