I have two containers in a view. The top view is a collection view. I want to update the collection view with one button when the button from the container below is clicked. My button also changes the value of the array that my collection view uses.
I thought that didSet would do the job, but unfortunately does not work.
Top:
class TopViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var favoritesCV: UICollectionView!
var myFavorites = [] {
didSet {
self.favoritesCV.reloadData()
}
}
override func viewDidAppear(animated: Bool) {
myFavorites = favoritesInstance.favoritesArray
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return myFavorites.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : FavoritesCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! FavoritesCollectionViewCell
var myPath = myFavorites[indexPath.row] as! String
cell.myImage.image = UIImage(named: myPath)
return cell
}
}
Bottom:
class BottomViewController: UIViewController, UIScrollViewDelegate {
@IBAction func addFavorites(sender: AnyObject) {
favoritesInstance.favoritesArray.append("aaaa.jpg")
}
}
Storage class:
class Favorites {
var favoritesArray:Array <AnyObject>
init(favoritesArray:Array <AnyObject>) {
self.favoritesArray = favoritesArray
}
}
var favoritesInstance = Favorites(favoritesArray:[])
source
share