UICollectionViewCell 是否有 viewWillAppear 或我可以将数据传递给的东西

Does UICollectionViewCell have a viewWillAppear or something I can pass data to

我的视图控制器中有这个:

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     CellSubclass *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

     cell.dataObjects = data;

     return cell;
}

在我的 CellSubclass.m 我有:

- (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;
}

所以在我的视图控制器的生命周期中,CellSubclass 在数据准备好之前立即被调用。是否有像 viewWillAppear 这样的函数或我也可以传递数据的函数?除了 initWithFrame 之外,如何从我的视图控制器调用函数?我可以通过其他方式传递数据吗?

谢谢。

当您没有任何数据要显示时,您应该 return 将单元格数设置为 0。准备好数据后,只需重新加载集合视图即可。

在您的数据源方法中

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    if (self.collectionViewData)
        return self.collectionViewData.count; 
    else
        return 0;
}

假设您有一个异步网络调用并且它有 returned 数据。 在完成块中,只需重新加载集合视图。

-(void)fetchData {
    [httpClient fetchDataWithCompletionBlock:^(NSArray *data) {
        [self.collectionView reloadData];
    }];
}

cellForItemAtIndexPath 中的单元格使用自己的配置方法听起来更好。

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     CellSubclass *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" 
                                                                    forIndexPath:indexPath];

     cell.dataObjects = fetchedMUtableArray[indexPath.row];

     [cell somethingConfiguringMethods];

     return cell;
}

UICollectionViewCell 没有类似的东西,但它是 UIView 的子类,并且有 didMoveToSuperview。 我在某些特定情况下在生产中使用它,但无论如何它也有助于一些快速调试。

https://developer.apple.com/documentation/uikit/uiview/1622433-didmovetosuperview