简体   繁体   English

UITableView和UICollectionView更新新单元格问题

[英]UITableView and UICollectionView update new cells issue

I am trying to work with UICollectionView that is a part of the UITableViewCell. 我正在尝试使用UICollectionView,它是UITableViewCell的一部分。

So the issue I faced, the collection view for visible table cells works ok, but when I start scroll table and table starts create new cells that where invisible then I faces with some behaviour that duplicate first table cell. 因此,我面临的问题是,可见表单元格的集合视图可以正常工作,但是当我启动滚动表和表启动时,创建了新单元格,这些单元格在不可见的情况下会遇到与第一个表单元格重复的行为。 For example I have scrolled collection view in first table view cell, then I scrolled table view down, and what I see the new cell have the same state as my first cell had. 例如,我在第一个表格视图单元格中滚动了集合视图,然后向下滚动了表格视图,并且我看到的新单元格的状态与我的第一个单元格相同。 You can check source here repo and the video here to understand what I am talking about. 您可以在此处查看回购源和此处的视频 ,以了解我在说什么。

-[UITableViewCell prepareForReuse]

Have a property of UICollectionView in CustomTableViewCell.h and bind it in Main.storyboard. 在CustomTableViewCell.h中具有UICollectionView的属性,并将其绑定在Main.storyboard中。 Let's assume declared it like this: 假设这样声明:

@property (strong, nonatomic) UICollectionView *collectionView;

In ViewController.m change cellForRowAtIndexPath method, so it reloads inside UICollectionView every time it need 在ViewController.m中,更改cellForRowAtIndexPath方法,以便每次需要时在UICollectionView中重新加载

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomTableViewCell"];

    [cell.collectionView reloadData];
    [cell.collectionView scrollRectToVisible:CGRectZero animated:NO];

    return cell;
}

Of course, you need to import CustomTableViewCell.h on ViewController.m file. 当然,您需要在ViewController.m文件上导入CustomTableViewCell.h

Problem with reuse identifier in UITableView cell, if you use single cell identifier in cellForRowAtIndexPath this problem will occurs UITableView单元中重用标识符的问题,如果在cellForRowAtIndexPath中使用单个单元标识符,则会出现此问题

1. Use Dynamic cell identifier for each row, like this 1.像这样对每一行使用动态单元格标识符

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"CustomTableViewCell_%d",indexPath.row]];
}

2.Store content offset for each collection view in array, and reset collection view content offset 2.将每个集合视图的内容偏移量存储在数组中,并重置集合视图内容的偏移量

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ......
    [cell.collectionView setContentOffset:scrollingPoint animated:NO];

    return cell;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM