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

前端 未结 5 1398
栀梦
栀梦 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 09:00

    Yes--this is entirely possible. You can either assign their respective UICollectionViewDelegates/UICollectionViewDataSources to different classes or subclass the CollectionViews, assigning both the delegate and data source to your current viewController and downcast your reference to collectionView in the delegation methods like so:

    @IBOutlet collectionViewA: CustomCollectionViewA!
    @IBOutlet collectionViewB: CustomCollectionViewB!
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
        if let a = collectionView as? CustomCollectionViewA {
            return a.dequeueReusableCellWithIdentifier("reuseIdentifierA", forIndexPath: indexPath)
        } else {
            return collectionView.dequeueReusableCellWithIdentifier("reuseIdentifierB", forIndexPath: indexPath)    
        }
    }
    

    Subclass UICollectionView like this:

    class CustomCollectionViewA: UICollectionView {
        // add more subclass code as needed
    }
    
    class CustomCollectionViewB: UICollectionView {
        // add more subclass code as needed
    }
    

提交回复
热议问题