Does UICollectionViewCell have a viewWillAppear or something I can pass data to
Solution 1
It sounds better to use your own configure method for cell in cellForItemAtIndexPath.
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CellSubclass *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier"
forIndexPath:indexPath];
cell.dataObjects = fetchedMUtableArray[indexPath.row];
[cell somethingConfiguringMethods];
return cell;
}
Solution 2
UICollectionViewCell does not have something like that, but that is a subclass of UIView and that one has didMoveToSuperview. I use it in production for some specific cases, but anyway it helps for some fast debugging also.
https://developer.apple.com/documentation/uikit/uiview/1622433-didmovetosuperview
Solution 3
You should return the number of cells as 0
when you do not have any data to show. When you have the data ready just reload collection view.
In your datasource methods
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section {
if (self.collectionViewData)
return self.collectionViewData.count;
else
return 0;
}
Lets say you have an async network call and it has returned data. In the completion block just reload collection view.
-(void)fetchData {
[httpClient fetchDataWithCompletionBlock:^(NSArray *data) {
[self.collectionView reloadData];
}];
}
cdub
Updated on June 04, 2022Comments
-
cdub almost 2 years
I have this in my view controller:
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { CellSubclass *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; cell.dataObjects = data; return cell; }
In my CellSubclass.m I have:
- (id) initWithFrame:(CGRect)frame { // You can call initWithFrame: method here as our base constructor of the UIView super class self = [super initWithFrame:frame]; if (self) { // call functions that need access to data but data is nil } return self; }
So in the lifecycle of my view controller, the CellSubclass gets called immediately before the data is ready. Is there a function like viewWillAppear or something that I can pass the data too? How can I call a function from my view controller other than initWithFrame? Can I pass the data in other ways?
Thanks.