I'm having trouble passing data from my model to a collection view. I've simplified my code to a simple project to illustrate the problem, which is available here: https://github.com/routineCode/collectionViewDataProblem
Here is an image showing the Desired Result vs. Actual Result with the current code: View Controller output showing Desired vs. Actual Result
I want the collectionView(numberOfItemsInSection) function to return the number of items (5) in my [data] array but it instead returns the hard-coded value (3). Through debugging, I realize that this is because viewController is always nil when this function is called, but I don't understand how to get around the problem. I also make use of the [data] array in the collectionView(cellForItemAt) function, and that works fine because viewController is not nil by the time that function is called. Thanks for any help.
Try to reloadData after you set the ViewController
lazy var menuBar: MenuBar = {
let mb = MenuBar()
mb.viewController = self
mb.cView.reloadData()
return mb
}()
By the way, your code has problem with memory leak
Retain circle
Retain circle is when two objects has strong reference to each other, so no one never deallocates. Here is an example of retain circles that is right exactly the same as yours.
In your Code the ViewController has a strong reference to menuBar
lazy var menuBar: MenuBar ...
And MenuBar has a strong reference to ViewController
var viewController: ViewController?
You can set the viewController property to weak, but what for you give the whole ViewController? Why your menuBar should know about the whole viewController? You can just remove the viewController property and give it a data property instead.
let data = [String]()
And set it in your viewController
lazy var menuBar: MenuBar = {
let mb = MenuBar()
mb.data = data
return mb
}()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.