【问题标题】:Does UICollectionViewCell have a viewWillAppear or something I can pass data toUICollectionViewCell 是否有 viewWillAppear 或我可以将数据传递给的东西
【发布时间】:2015-11-12 06:04:21
【问题描述】:

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

- (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 之外的函数?我可以通过其他方式传递数据吗?

谢谢。

【问题讨论】:

  • 在完成块中使用 reloadCollectionView 方法听起来更好,该方法在您的数据获取完成时调用。

标签: ios objective-c uiviewcontroller uicollectionview uicollectionviewcell


【解决方案1】:

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

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

     cell.dataObjects = fetchedMUtableArray[indexPath.row];

     [cell somethingConfiguringMethods];

     return cell;
}

【讨论】:

  • 我太棒了,那是 [cell somthingConfiguringMethods] 并且 somethingConfiguringMethods 在 CellSubclass 中正确吗?
  • 哦,对不起,是的。 somthingConfiguringMethods 在单元实现文件中定义。
【解决方案2】:

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

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

【讨论】:

  • 这正是我需要的,以便在加载视图后让我进行一些约束修改。谢谢@鲍里斯
【解决方案3】:

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

在您的数据源方法中

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

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

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

【讨论】:

  • 哪个函数在:- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  • @chris 那是你UICollectionView的数据源方法
  • 好的,没错。如何将数据传递给 CellSubclass 并在 initWithFrame 中使用它
  • 我有一个解析 PFQuery,它在我的视图控制器 viewDidLoad 和 viewDidScroll 中加载一个 NSMutableArray
  • 不确定如何从视图控制器中的 NSMutableArray 获取数据到使用 initWithFrame 中的数据的子类 UICollectionViewCell
猜你喜欢
  • 2012-05-08
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
相关资源
最近更新 更多