How to programatically switch the data source of a collection view?

i Have successfully displayed different images using uicollectionview. Now I have a question, how do I dynamically switch the data source of a collection view using a few buttons ? Please help :slight_smile:

Thank you

Hello and welcome to the community!

On the tap of the button, you can programmatically change the data that the collection view is pointing to and then call the reloadData() method on it to make it request the data again from the view controller!

Wow finally I found the answer. Thank you Chris. Let me give it a try

Just a side note. Is protocol and delegate applicable in making this work?

import UIKit
import Messages

class MessagesViewController: MSMessagesAppViewController {

let stickerCategoryArray = ["Everyday1","Happy"]
var selectedCategory = "Everyday1"

@IBOutlet weak var StickerCollectionView: UICollectionView!

@IBAction func everydayButtonPressed(_ sender: Any) {
    selectedCategory = stickerCategoryArray[0]
    print(selectedCategory)
    reloadView()
}

@IBAction func happyButtonPressed(_ sender: Any) {
    selectedCategory = stickerCategoryArray[1]
    print(selectedCategory)
    reloadView()
}

func reloadView (){
    StickerCollectionView.reloadData()
}

override func viewDidLoad() {
    super.viewDidLoad()
    reloadView()
    // Do any additional setup after loading the view.
}

extension MessagesViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
10
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StickerCell", for: indexPath) as! StickerCollectionViewCell
    
    cell.setupStickers(indexPath: indexPath, selectedCategory: selectedCategory)
    
    return cell
}

This is what I have come up with. My stickers did load properly but when i click on the buttons the collection view dosenโ€™t reload. Did I call the reloadData at the wrong place?