我怎样才能使 Collection View 中的单元格自动调整大小,以便至少四个单元格可以放在一行中,如果框架大小是 iPad 的,那么更多的单元格可以放在一行中。四个单元格应该是一行中的最小单元格数,请参阅下面的图片以进一步说明:
我有一个 Collection View ,它允许我使用选择器 View Controller 添加图像,起初 Collection View 如下所示:
我可以进一步向这个 Collection View 添加图像,在添加多张图像后,它会:
现在如果有四张图片,第四张转到下一行,我希望系统根据帧大小自动调整单元格大小,以便一行中至少显示四个单元格。我是新手,对收藏 View 还很陌生,有人可以帮我解决这个问题吗?
最佳答案
您可以使用以下方法决定 collectionview 单元格的大小:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
// Return different cells size
let screenBounds = UIScreen.main.bounds
var width = screenBounds.width
let totalLeftRightInsect = 16
let minimumsSpaceBetweenCell = 5
switch (Condition for detecting device ) {
case "iPhone":
let numberOfCell = 4
let totalSpace = CGFloat(( numberOfCell * spaceBetweenCell) + totalLeftRightInsect)
width = (width - totalSpace) / CGFloat(numberOfCell)
return CGSize(width: width, height: width)
case "ipad":
let numberOfCell = 6
let totalSpace = CGFloat(( numberOfCell * spaceBetweenCell) + totalLeftRightInsect)
width = (width - totalSpace) / CGFloat(numberOfCell)
return CGSize(width: width, height: width)
default:
return CGSize(width: 0.0, height: 0.0)
}}
关于ios - 根据框架大小自动调整 UICollectionViewCell 中的单元格大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230257/