2017-10-11 51 views
2

我是iOS開發的初學者,我正在學習一個教程來實現集合視圖。UICollectionView項間距無法調整

下面是該應用的截圖:

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

但差距仍大。這裏出了什麼問題?

+0

這可能幫助你。 https://stackoverflow.com/questions/35654129/how-to-change-space-between-cells-in-uicollectionview/35654505#35654505 –

+0

imageView是否填滿每個單元格?您可以使用Debug View Hierarchy來檢查它 – jojoT

回答

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. 
} 
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 

}

希望這有助於