如何在一个视图控制器中合并多个集合视图?

5 iphone ios uicollectionview swift

多个集合视图

我正在尝试使用 UICollectionViews 获得七个水平可滚动按钮栏。我在启动和运行一个按钮栏时没有问题,但是当我使用多个集合视图时,我遇到了应用程序崩溃错误。有没有人知道如何在 Swift 中实现这一点或知道任何教程?我的第一个集合视图的代码在这里:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    var tableImages: [String] = ["1.png", "2.png", "3.png", "4.png", "5.png", "6.png"]

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

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell:CollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
        cell.expansionCell.image = UIImage(named: tableImages[indexPath.row])
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        println("cell \(indexPath.row) selected")
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮忙!

kei*_*ter 1

要分离逻辑,您可以创建 3 个数据源对象来填充集合视图。每个数据源都可以处理其集合视图的所有单元逻辑。这将使您的视图控制器不那么混乱,因为您所要做的就是将它们全部分配在viewDidLoad. 您将需要保留对数据源对象的引用,因为collectionView.dataSource不会。

var collectionViewA: UICollectionView!
var dataSourceA: DataSourceA!
var collectionViewB: UICollectionView!
var dataSourceB: DataSourceB!
var collectionViewC: UICollectionView!
var dataSourceC: DataSourceC!

override func viewDidLoad() {
    super.viewDidLoad()
    self.dataSourceA = DataSourceA()
    self.collectionViewA.dataSource = self.dataSourceA
    // repeat for dataSource/collectionView B and C
}
Run Code Online (Sandbox Code Playgroud)