4

我在使用UICollectionView. 我有这个数组viewDidLoad来填充UICollectionView.

array = [[NSMutableArray alloc] init];
[array addObject:@"1"];
[array addObject:@"2"];
[array addObject:@"3"];
[array addObject:@"4"];
[array addObject:@"5"];
[array addObject:@"6"];

和方法:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"Cell";
    //cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    myCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 100, 20)];
    [titleLabel setText:[array objectAtIndex:indexPath.row]];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    [cell addSubview:titleLabel];

    return cell;
}

我点击UIButton并重新加载数据:

[myCollectionView reloadData];

以下是重新加载前后数据的样子: 前

后

4

4 回答 4

12

每次点击重新加载按钮时都会添加一个新标签。您应该添加一次标签并相应地更改标签文本。

这里举一个简单的例子。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    MyCell *cell = (MyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
                                                                               forIndexPath:indexPath];
    [cell setMyTextLabel:indexPath.row];
    return cell;
}

其中MyCell将包含一个UILabel和一个属性来修改其文本。

我真的建议看看@Ben Scheirman 的UICollectionView代码的乐趣

希望有帮助。

PS重命名myCellMyCell。一个类应该以大写字母开头。

于 2013-05-13T08:51:07.440 回答
1

当您点击重新加载按钮时,您正在添加标签。在这种情况下,您将一次又一次地添加标签...

所以有三种解决方案:

  • 让您的细胞可重复使用
  • 在 reload 方法中从 superview 中删除您的单元格。
  • 您可以检查标签的text长度是否不等于零。在这种情况下,无需添加该标签并更改文本。
于 2013-05-13T08:46:21.633 回答
1
 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
 {
       UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
dispatch_async(dispatch_get_main_queue(), ^{

  //  ********* Changed *******

        for (UIView *v in [cell.contentView subviews])
        [v removeFromSuperview];

 // ********** Changed **********
            if ([self.collectionviewFlow.indexPathsForVisibleItems containsObject:indexPath]) {
            NSString *img_name=[NSString stringWithFormat:@"%@_thumb%d.png",self.VaritiesName,(int)indexPath.row+1];
            imageVw=[[UIImageView alloc]initWithImage:[UIImage imageNamed: img_name]];
            imageVw.frame=CGRectMake(10,10,100,100);
            [cell.contentView addSubview:imageVw];
            }
       });
     cell.backgroundColor=[UIColor clearColor];
     return cell;
}
于 2013-10-29T09:00:02.563 回答
0

已经很晚了,但这是我的解决方案。

如果您使用自定义 collectionviewcell,请尝试使用 'func prepareForReuse()'

于 2016-06-16T06:02:13.700 回答