Ios UICollectionView项目间距可以';不可调整

Ios UICollectionView项目间距可以';不可调整,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我是iOS开发的初学者,我正在遵循一个教程来实现集合视图 以下是该应用程序的屏幕截图: 我想尽可能缩小项目之间的差距。我已尝试实现以下代码: struct StoryBoard { static let leftAndRightPaddings : CGFloat = 1.0 static let numberOfItemsPerRow : CGFloat = 3.0 } let collectionViewWidth = collectionView?.frame.widt

我是iOS开发的初学者,我正在遵循一个教程来实现集合视图

以下是该应用程序的屏幕截图:

我想尽可能缩小项目之间的差距。我已尝试实现以下代码:

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,如下所示:


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

您可以使用
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个像素也会导致布局混乱。@iPatel-answer几乎没有变化

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 
}


希望这对你有所帮助。imageView是否在每个单元格上填充?您可以使用调试视图层次结构来检查它