How do I include multiple views of a collection in one view controller?

Multiple Collection Views

I am trying to get seven horizontal scrollable buttons using UICollectionViews. I have no problem launching and launching a single button bar, but I am facing application crash errors when I use multiple collection views. Does anyone know how to do this in Swift, or inquire about any tutorials? My code for the first kind of collection is presented here:

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")
    }
}

      

Please, help!

+3


source to share


2 answers


To decouple the logic, you can create 3 data source objects to populate the collection views. Each data source can process all the cell logic for its collection view. This will make your view controller less confusing, as all you have to do is assign them all in viewDidLoad

. You will need to keep a reference to the data source objects as collectionView.dataSource

there won't be.



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
}

      

+1


source


This is how I did my job. hope this helps you.

points:

@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var SecondCollectioView: UICollectionView!

      



Method:

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

    if(collectionView == self.SecondCollectioView) {
        cell.backgroundColor = UIColor.black
    } else {
         cell.backgroundColor = self.randomColor()
    }

    return cell;
}

      

0


source







All Articles