2

我試圖編輯這個單元格的寬度,這樣無論屏幕大小如何,我都會在一行中有score1.count個單元格。我用於收集視圖的代碼如下:編輯一個CollectionViewCell的寬度

func numberOfSections(in collectionView: UICollectionView) -> Int { 
    return 1 
} 
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return self.items.count 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell 

    cell.myLabel.text = String(self.items[indexPath.item]) 

    return cell 
} 

這是針對單元格寬度的函數。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize { 
    let size = Int(self.view.frame.size.width)/(score1.count + 1) 
    return CGSize(width: CGFloat(size), height: 80) 
} 

我花了很多時間看着不同的來源和嘗試不同的事情,但收集視圖從來沒有正確數量的單元格。一個想法是,它可能是因爲我有自動佈局設置單元格大小,但每當我去改變它xcode崩潰。任何想法繞過自動佈局?或者如何改變自動佈局?

謝謝!

+0

你設置'UICollectionViewFlowLayout'? –

+0

不,但我沒有在代碼中引用它。 –

+1

將UICollectionViewDelegate更改爲UICollectionViewDelegateFlowLayout並且它工作正常!多謝你們! –

回答

0

試試這個

extension YourViewController : UICollectionViewDelegateFlowLayout{ 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    let rowItems:CGFloat = 4 
    let padding:CGFloat = 2 
    let width = (collectionView.bounds.width/rowItems) - padding //Change width as per your requirement 
    let height = collectionView.bounds.height - (2 * padding)//Change height as per your requirement 
    return CGSize(width: width, height: height) 
    } 

} 
+0

我確定這些答案都能正常工作,但它仍然符合我在故事板佈局選項中指定的內容。我如何覆蓋它?保持空白?還是有一行代碼我錯過了別的地方? –

0

您可以將您的sizeForItemAtIndexPath更改爲。您可以在減少邊距和按單元數量分配之後指定單元格的大小。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize { 
     let size = (Int(collectionView.bounds.width) - (score1.count+1)*5) /(score1.count) // 5 is the margin you want to keep in between 2 cells 
     return CGSize(width: CGFloat(size), height: 80) 
    } 

如果您有任何疑問,請告訴我。我會盡力澄清。

+0

在5之後有一個過多的括號。它的效果更好,但仍然比score1.count多一個。 –

+0

葉普我的錯誤。實際上遠離我的系統,我從移動設備中獲取它。 「它效果更好,但比分數還要多一分。」那是什麼意思。 – luckyShubhra

+0

你是怎麼得到 – luckyShubhra

相關問題