Eseye Eseye - 1 month ago 15
Swift Question

How to change data of a NSCollectionView with buttons

I have data that is coming in via JSON and I was able to switch the data in my collection view based off some logic. If I am logged in it shows one set of data and if I log out it shows another set of data. But now I want to change the data of my collection view based on button pushes. I have two buttons. One shows "All Products" and the other shows "Installed Products" How can I incorporate button pushes to switch between my data?

CollectionView Logic

extension ViewController: NSCollectionViewDataSource, NSCollectionViewDelegate, NSCollectionViewDelegateFlowLayout{


func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {

let prefs:UserDefaults = UserDefaults.standard
let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

if (isLoggedIn == 1) {


return installedArray?.count ?? 0
}

return productsArray?.count ?? 0
}


func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {

let prefs:UserDefaults = UserDefaults.standard
let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

if (isLoggedIn == 1) {


let item = collectionView.makeItem(withIdentifier: "Installed", for: indexPath) as! Installed

item.buildProduct = installedArray?[indexPath.item]

return item
}

let itemB = collectionView.makeItem(withIdentifier: "test1", for: indexPath) as! test1

itemB.buildProduct = productsArray?[indexPath.item]

return itemB

}


Buttons

@IBAction func allAppsPushed(_ sender: Any) {

let prefs:UserDefaults = UserDefaults.standard
let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

if (isLoggedIn == 1) {




}else{


}


}

@IBAction func installedPushed(_ sender: Any) {

let prefs:UserDefaults = UserDefaults.standard
let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

if (isLoggedIn == 1) {



}else{



}
}

Answer

Try calling collectionView.reloadData() in your button methods. That will cause the collectionView to completely reload it's data, and since your isLoggedIn flag has changed states, you should load different data.