2017-07-16 32 views
0

我想通過使用UICollectionViewCell實現以下圖像。 Sample Image如何在swift3中的UICollectionView中顯示兩個不同的單元格

但我對此有3種不同的情況: A)一個特定類型的旅程只有前進的旅程時間是可見的。 B)可以看到特定類型的前進旅程和返程旅程(如下圖所示)。 C)特定類型的旅程有2次往返旅程和2次回程旅行時間。

所以我想爲此使用集合視圖。我是否正確地使用這種方法以及如何使用集合視圖實現這一邏輯?

回答

3

我可能繼承我的UICollectionViewCell,定義所有必需的佈局類型枚舉並將其作爲參數傳遞給自定義方法中的cellForItemAtIndexPath,因此自定義集合視圖單元格知道如何佈局自身。

事情是這樣的:

enum MyLayoutType 
{ 
    case layoutA 
    case layoutB 
    case layoutC 
} 

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource 
{ 
    override func viewDidLoad() 
    { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() 
    { 
     super.didReceiveMemoryWarning() 
    } 

// MARK: Collection View DataSource 

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

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    { 
     return 10 
    } 

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

     // Decide here what layout type you would like to set 

     cell.setUpWithType(layoutType: .layoutA) 
     return cell 
    } 
} 

,然後在您的自定義集合視圖細胞亞類(不要忘了指定自定義類在你的界面生成器文件):

class MyCustomCVCell: UICollectionViewCell 
{ 
    func setUpWithType(layoutType: MyLayoutType) 
    { 
     switch layoutType 
     { 
     case .layoutA: 
      self.backgroundColor = .red 
     case .layoutB: 
      self.backgroundColor = .yellow 
     case .layoutC: 
      self.backgroundColor = .blue 
     } 
    } 
} 
+0

你能不能請張貼一些代碼或它的github項目? –

+0

我編輯了我的答案,並添加了一個簡單的例子。 –

相關問題