在 uitableviewcell 中使用 uicollectionview

Posted

技术标签:

【中文标题】在 uitableviewcell 中使用 uicollectionview【英文标题】:Use uicollectionview inside uitableviewcell 【发布时间】:2014-03-11 13:02:44 【问题描述】:

我无法解决下一个问题。

我想显示 20 个表格单元格,每个单元格都包含一个唯一的UICollectionView

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    
        NSDictionary *package=[_packageList objectAtIndex:indexPath.row];
        static NSString *CellIdentifier = @"package";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        UICollectionView *cellImageCollection=(UICollectionView *)[cell viewWithTag:9];
        cellImageCollection.restorationIdentifier=[NSString stringWithFormat:@"%li", (long)indexPath.row, nil];

        cellTracking.text=[NSString stringWithFormat:@"Row #%li",(long)indexPath.row];
        return cell;
    


-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
    int row=[collectionView.restorationIdentifier intValue];
    return [[[_packages objectAtIndex:row] valueForKey:@"imageGallery"] count];

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    int row=[collectionView.restorationIdentifier intValue];
    NSString *imgStrLink=[[[_packages objectAtIndex:row] valueForKey:@"imageGallery"] objectAtIndex:indexPath.row];
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageID" forIndexPath:indexPath];
    UIImageView *imageView=(UIImageView *)[cell viewWithTag:2];
    imageView.image=....;
    return cell;

函数tableView:cellForRowAtIndexPath:被调用了20次,但collectionView:numberOfItemsInSection:collectionView:cellForItemAtIndexPath:只被调用了4次。 如屏幕截图所示,UICollectionView 每四行重复一次。

我的错是什么?

【问题讨论】:

使用自定义 tableviewcell,为其创建一个子类,将您的 collectionview 委托/数据源添加到单元格的子类中。我自己并没有这样测试它,但是我使用了一个包含另一个集合视图的集合视图单元格并且它起作用了。 不要使用单元格作为数据源和委托。 Cell不应该负责提供这样的东西。最好将集合视图子类化并添加名为 index 的属性,然后在委托和数据源方法中检查索引。将您的视图控制器用于集合视图委托和数据源。 【参考方案1】:

我也遇到过这个问题,我遇到这个问题的原因是tableview和collectionView的数据源和委托都属于同一个父视图控制器。

当我将 collectionView 的数据源和委托更改为另一个 View 时,它开始为我工作,例如 ParentView,我将 collectionView 添加到此 ParentView,然后最后将 ParentView 添加为单元格的 conentView。

有人说我应该在此处包含内容的基本部分(因为该链接将来可能会变得无效)删除了我之前指向两个不错的教程的答案...但是我不能这样做,因为这些是代码由教程所有者编写,整个代码也很重要:),所以现在我给出源代码的链接......

HorizontalCollectionViews

AFTabledCollectionView

-anoop

【讨论】:

@anoop4real,兄弟你能帮我解决我的问题***.com/questions/44650058/… 吗?【参考方案2】:

从 Xcode 7 和 ios9 开始,您可以使用 UIStackView - 如果 collectionview 或 tableview 相互包含,则为设计的最佳解决方案。

【讨论】:

使用UIStackView听起来很有趣。请问有代码示例吗? 最佳教程raywenderlich.com/114552/…

以上是关于在 uitableviewcell 中使用 uicollectionview的主要内容,如果未能解决你的问题,请参考以下文章

从 uic 输出到 Qt 中的 C++ 代码

pyside-uic 在哪里?

UICollectionView 作为子视图不会更新约束

如何使用cmake强制UIC在源目录中生成ui_mainwindow.h

pyside-uic/pyuic4:找不到命令

如何在不导入自定义小部件类包的情况下使用自定义小部件和 uic.loadUi?