1

如何使集合視圖中的單元格自動調整大小,使至少四個單元格至少可以放入單個行中,並且如果幀大小是iPad的大小,那麼更多的細胞可以適應行。四個單元格應該是連續單元格的最小數量,請參閱下面的圖片以獲得進一步的說明:根據幀大小自動調整UICollectionViewCell中的單元格

我有一個集合視圖,它允許我通過使用選取器視圖控制器添加圖像,首先集合視圖看起來像這樣:

enter image description here

我的圖像中添加到此集合視圖,並添加一些圖片後,它想:

enter image description here

現在,如果有四個圖像,第四個圖像會進入下一行,我希望系統根據幀大小自動調整單元格大小,以便在一行中顯示最少四個單元格。我是一個新手,收集視圖相當新,有人可以幫助我嗎?

回答

0

您可以用下面的方法決定的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) 
    }} 
0

答案Swift3,Xcode中8 horizantal間距固定:

與先前的所有回答的問題是,單元尺寸給定CGSizeMake(cellWidth,cellWidth)實際上將所有屏幕都留空,因此collectionView會嘗試通過減少每行中的一個元素和不需要的額外間距來調整行/列間距。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
     let linespacing = 5   //spacing you want horizantally and vertically 
     let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat 
     let cellWidth = UIScreen.mainScreen().bounds.size.width/numberOfCell 
     return CGSizeMake(cellWidth - linespacing, cellWidth - linespacing) 

}

相關問題