0

I'm constructing a tabView with a collectionView as one of the tabs. In the tabView, I have a button that takes a Photo and adds it to the collection view. The problem I'm facing is reloading the collection view from the TabView, because I'm getting the following error: "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'"

In the TabView I'm calling this function: PhotoListController().reloadData()

And in the PhotoListController, that function is:

func reloadData() {
    getData() //function that goes through an array with the data of the images
    self.collectionView!.reloadData()
}

When I had everything in the same class, it worked pretty well, but now I can't fix the problem :(

If anybody can give me a hand it would be very much appreciated.

Gosdi
  • 39
  • 4

2 Answers2

0

Well I've finally found a solution within this topic: How to reload data in a TableView from a different ViewController in Swift

and this one:

Swift: Reload collection view data from another view class with swift

The solution is related to use a NotificationCenter

Community
  • 1
  • 1
Gosdi
  • 39
  • 4
0

in this code: PhotoListController().reloadData() you create a new copy of PhotoListController class, but you need to apply to the same instance of PhotoListController class that was already been created. I guess you need to apply the delegate pattern.

protocol PhotoListDelegate: AnyObject {
    func reloadData()
}

class PhotoListController : UIViewController, PhotoListDelegate {
    var tableView = TableView()
    var collectionView = UICollectionView()
    
    override func viewDidLoad() {
        tableView.photoListDelegate = self
    }
    func reloadData() {
        getData()
        self.collectionView.reloadData()
    }
    
    func getData() {
        // your code to get data
    }
}

class TableView: UITableView {
    weak var photoListDelegate : PhotoListDelegate?
    
    
    // then in TableView Class:
    
    func photoCatched() {
        self.photoListDelegate?.reloadData()
    }
}

Lenny
  • 23
  • 6