UICollectionView 数据被重新排序

Posted

技术标签:

【中文标题】UICollectionView 数据被重新排序【英文标题】:UICollectionView Data being Reordered 【发布时间】:2013-04-13 22:34:15 【问题描述】:

我正在使用带有 LXReorderableCollectionViewFlowLayout 修改版本的 UICollectionView,并且我最后两个单元格中的数据被混淆了。

每个单元格中显示2个单独的图像,下面有一个标签,当我离开viewController并返回时,我调用reloadData。每次调用时,单元格中的图像都会交换。但是,标签保留在同一个位置。

这是我用来绘制有问题的单元格的代码。

SettingsTile *setTileD = (SettingsTile *)[collectionView dequeueReusableCellWithReuseIdentifier:@"settingsReuse" forIndexPath:indexPath];

    NSString *songTitle = [colors objectAtIndex:indexPath.row];

    MPMediaQuery *query = [MPMediaQuery songsQuery];
    [query addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:songTitle forProperty:MPMediaItemPropertyTitle]];
    if ([query items].count > 0)
    
        MPMediaItemArtwork *art = [[[query items] objectAtIndex:0] valueForProperty:MPMediaItemPropertyArtwork];
        UIImage *im = [art imageWithSize:CGSizeMake(145, 145)];

        setTileD.titleLabel.text = songTitle;
        setTileD.titleLabel.textColor = [UIColor whiteColor];
        UIImageView *imView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 145, 145)];
        imView.image = im;
        [setTileD addSubview:imView];
        [setTileD sendSubviewToBack:imView];
        return setTileD;
    
    else
    
        return nil;
    

第一次运行应用程序时,图像被混淆了,可能是因为在第一次显示 viewController 时也调用了 viewDidAppear,当用户返回它时,图像没有被混淆。这个过程会不断重复。

reloadData 被正常调用(例如 [collectionView reloadData]; )。

我是 UICollectionView 的新手,它是附带的类,所以请善待。 :)

【问题讨论】:

【参考方案1】:

我通过将 UIImageViews 放在 backgroundView 中解决了这个问题,而不是直接将它们添加为子视图。

我只能想象这个问题是由 UICollectionView 的 cellForRowAtIndexPath: 方法在我调用它们时抓取图像的方式引起的,或者是由 LXReorderableCollectionViewFlowLayout 的工作方式引起的。

【讨论】:

你能解释一下,你所说的“..将 UIImageViews 放入 backgroundView ..”是什么意思?谢谢 我用它来解决类似的问题。在 cellForItemAtIndexPath 中,我使用了:cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];

以上是关于UICollectionView 数据被重新排序的主要内容,如果未能解决你的问题,请参考以下文章

UICollectionView 单元格重新排序

保存重新排序的uicollectionview单元格无法正常工作

重新排序 UICollectionView 的单元格

如何在锁定其中一些单元格时重新排序 UICollectionView 单元格

UICollectionView 与 SwiftUI + 拖放重新排序可能吗?

UICollectionView 单元格的水平重新排序