2017-07-16 30 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

我编辑了我的答案,并添加了一个简单的例子。 –

相关问题