UICollectionViewCell中的子视图控制器

lim*_*boy 6 objective-c ios childviewcontroller uicollectionview

假设我想要实现Pinterest的pin页面,就像这样:

Pinterest的

这是我的方法:

  1. 做一个UICollectionViewController,pin的页面是一个UICollectionViewCell
  2. cell由两个组成:pin info child vc && waterfall child vc

然后出现了问题:如何重用子视图控制器?

一些伪代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    Pin *pin = self.dataSource[indexPath.row];
    // i have to create a new childVC, based on different indexPath.
    UITableViewController *pinInfoViewController = [[pinInfoViewController alloc] initWithPin:pin];
    [cell updatePinViewWithPin:pin];
    [self addChildViewController:pinInfoViewController];

    // Add waterfall view controller
}
Run Code Online (Sandbox Code Playgroud)

每次调用此方法时,都会创建一个新的子视图控制器,它没问题,或者如何改进它?

App*_*eyA 1

我解决这个问题的方法是子类化UICollectionViewCell并将您需要的 UI 组件添加到它作为 iVar。当您需要使用新数据更新 UI 时,您将像现在在伪代码中一样获取单元对象,然后调用您声明的方法,并将updateCellWithModel:其传递给数据源中保存的模型。在此方法中,您将执行一些简单的检查来检查 UI 元素是否已创建,并在需要时创建它们,在这些类型的方法中进行健全性检查总是一个好主意,但元素应该在 init 方法中创建,并且将永远在那里。

编辑:我相信我回答了您的问题,但它仍然让我感到困惑,请添加更多信息,以便我可以在需要时编辑我的答案。