2015-09-14 107 views
4

我有一個集合View和每個collectionViewCell中的圖像。我想只有3個單元對於任何給定的幀/屏幕尺寸。我如何實現這一點。我已經寫了一些基於this postUICollectionViewCell根據屏幕/ FrameSize大小Swift

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 

    let numberOfCell = 3 
    let cellWidth: CGFloat = [[UIScreen mainScreen].bounds].size.width/numberOfCell 
    return CGSizeMake(cellWidth, cellWidth) 
    } 

但它不工作,並給出錯誤。做這個的最好方式是什麼。

回答

7

這是您的SWIFT代碼:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 

    let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat 
    let cellWidth = UIScreen.mainScreen().bounds.size.width/numberOfCell 
    return CGSizeMake(cellWidth, cellWidth) 
} 

這裏numberOfCell的類型必須是CGFloat因爲UIScreen.mainScreen().bounds.size.width回報CGFloat值,所以如果你想將其與numberOfCell劃分然後鍵入numberOfCell必須CGFloat因爲你可以不要將CGFloatInt分開。

+1

...如果我會這樣做,細胞之間就會有間隙......我不想要,我想要在所有屏幕和所有方向上水平和垂直5 px間隙。細胞的數量按照這個順序增加和減少。你能幫忙嗎? – Saty

+0

沒有爲我工作。 –

+0

不要忘記添加「UICollectionViewDelegateFlowLayout」,而添加委託類 - @JayprakashDubey –

6

這是斯威夫特3碼,你有實現UICollectionViewDelegateFlowLayout

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat 
      let cellWidth = UIScreen.main.bounds.size.width/numberOfCell 
      return CGSize(width: cellWidth, height: cellWidth) 
} 
+0

不要忘記添加「UICollectionViewDelegateFlowLayout」,同時添加委託類 –

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) 
} 
相關問題