2015-09-28 83 views
0

如何製作UICollectionView自動佈局,以便根據項目總數決定在某個時刻出現在屏幕上的項目數量。我真的想做出這樣的佈局,如果我有9個項目,而不是所有9個項目應該同時顯示在集合視圖上。如果項目是8或其他東西,那麼項目的大小應該增加,以至於它們仍然佔用收集視圖的完整區域。如何製作UICollectionView自動佈局

我策劃了該條件爲下:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    var cell = collectionView.cellForItemAtIndexPath(indexPath) as CollectionViewCell 

    if((cell.selected) && (indexPath.row%2 == 0)) 
    { 
     cell.backgroundColor = UIColor.whiteColor() 
     imageview.image = UIImage(named: a[indexPath.row]) 
    } 
    else if((cell.selected) && (indexPath.row%2 != 0)) 
    { 
     cell.backgroundColor = UIColor.whiteColor() 
     imageview.image = UIImage(named: a[indexPath.row]) 
    } 
} 

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
    var abc : CGSize! 
    if(a.count == 1){ 
     abc = CGSize(width: self.view.frame.width, height: self.view.frame.height/2) 
    } 
    else if(a.count == 2) { 
      abc = CGSize(width: self.view.frame.width/2, height: self.view.frame.height/2) 
    } 
    else if (a.count > 2) && (a.count<6){ 
     abc = CGSize(width: self.view.frame.width/3, height: self.view.frame.height/2) 
    } 
    else { 
     abc = CGSize(width: self.view.frame.width/3, height: self.view.frame.height/5) 
    } 
     return abc 
    } 

func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { 
    return true 
} 

func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool 
{ 
    return true 
} 

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { 
    return 1 
} 

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
      return a.count 
} 

func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { 
    return true 
} 

回答

1

從你的問題我知道你要非常的UICollectionView的單元尺寸,使他們覆蓋整個屏幕。

有很多方法可以實現你想要的,但關鍵是要使用UICollectionViewLayout。

例如,UICollectionViewFlowLayout具有itemSize屬性。

根據您的內容(細胞),你可以嘗試計算它們佔用的空間,然後設置的FlowLayout的itemSize財產。如果所有的細胞都應該是相同的大小,這應該足夠好。

您也可以使用委託方法collectionView:layout:sizeForItemAtIndexPath:設置每個單元格的大小。

如果這還不夠,因爲你想改變細胞的排列以及例如,您將需要繼承的FlowLayout以計算大小爲每個項目。看看這個: https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/UsingtheFlowLayout/UsingtheFlowLayout.html

最終,您需要首先根據您的內容首先計算需要多少個單元格。

+0

實際上,我想有細胞的數量爲動態,就像用戶可以上傳任何數量的圖片,並根據圖片的數量我的collectionView應顯示不同的安排..所以我不能確定項目的數量提前,它是完全動態的 – SameerVerma

+0

@SameerVerma,它是動態的,但在佈局實際完成之前您需要知道。因此,在您的示例中,一旦用戶完成上傳他的照片,您就會知道收藏視圖將具有多少個單元格。或者,如果你想在圖片後添加圖片(當用戶上傳圖片),你需要繼承layout對象的子類,以便在重新加載數據時重新設計單元格 – theprole