UICollectionView项目间距无法调整

时间:2017-10-11 04:47:11

标签: ios swift uicollectionview

我是iOS开发的初学者,我正在学习实现集合视图的教程。

以下是该应用的截图:

as we can see, the space between cell and line is quite big

我希望项目之间的差距尽可能接近。我试图实现以下代码:

struct StoryBoard {
    static let leftAndRightPaddings : CGFloat = 1.0
    static let numberOfItemsPerRow : CGFloat = 3.0
}

let collectionViewWidth = collectionView?.frame.width
let itemWidth = (collectionViewWidth! - StoryBoard.leftAndRightPaddings) / StoryBoard.numberOfItemsPerRow

let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)

我还在主故事板中将单元格和行的最小间距更改为0.1,如下所示:

minimimum spacing in storyboard

但差距仍然很大。这里出了什么问题?

2 个答案:

答案 0 :(得分:3)

您可以使用UICollectionViewDelegateFlowLayout方法

进行管理

对于EX。

使用以下方法进行管理

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = UIScreen.main.bounds.size.width
        var height = 124.0 // Set whatever you want
         return CGSize(width: (width / 3) - 0.5, height: CGFloat(height)) // Here (width / 3) means 3 cell display in screen horizontally. you can change here 3 or 2 or 4 etc AND "0.5" is space your can change space between two items that you want.
}

答案 1 :(得分:0)

您必须正确计算项目大小,因为即使1个像素也会导致布局受到干扰。 @iPatel回答的变化不大

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let noOfItemsInRow = 3 // the items in single row
    let width = UIScreen.main.bounds.size.width
    let totalSpace = 8 + 8 + (noOfItemsInRow * 0.5) //8: side margin, 0.5 is the space between 2 items
    var height = 124.0 // Set whatever you want
     return CGSize(width: ((width - totalSpace) / 3), height: CGFloat(height)) // Here (width / 3) means 3 cell display in screen horizontally. you can change here 3 or 2 or 4 etc 

}

希望这个帮助