How can I add multiple collection views in a UIViewController in Swift?

前端 未结 5 1397
栀梦
栀梦 2020-12-07 08:35

I tried many days to realise this: \"enter

I want to add in my UIViewController two di

5条回答
  •  既然无缘
    2020-12-07 08:57

    This is possible, you just need to add each UICollectionView as a subview, and set the delegate and dataSource to your UIViewController.

    Here's a quick example. Assuming you have one UICollectionView working, you should be able to adapt this code to your own uses to add a second fairly easily:

    let collectionViewA = UICollectionView()
    let collectionViewB = UICollectionView()
    let collectionViewAIdentifier = "CollectionViewACell"
    let collectionViewBIdentifier = "CollectionViewBCell"
    
    override func viewDidLoad() {
        // Initialize the collection views, set the desired frames
        collectionViewA.delegate = self
        collectionViewB.delegate = self
    
        collectionViewA.dataSource = self
        collectionViewB.dataSource = self
    
        self.view.addSubview(collectionViewA)
        self.view.addSubview(collectionViewB)
    }
    

    In the cellForItemAtIndexPath delegate function:

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        if collectionView == self.collectionViewA {
            let cellA = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewAIdentifier) as UICollectionViewCell
    
            // Set up cell
            return cellA
        }
    
        else {
            let cellB = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewBIdentifier) as UICollectionViewCell
    
            // ...Set up cell
    
            return cellB
        }
    }
    

    In the numberOfItemsInSection function:

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.collectionViewA {
            return 0 // Replace with count of your data for collectionViewA
        }
    
        return 0 // Replace with count of your data for collectionViewB
    }
    

提交回复
热议问题