Ios 设置集合视图单元格排序的动画

Ios 设置集合视图单元格排序的动画,ios,swift,xcode,cocoa-touch,uicollectionview,Ios,Swift,Xcode,Cocoa Touch,Uicollectionview,我试图在对数据源数组进行排序时,在UICollectionView中显示移动到位的单元格。我做了以下尝试,由于某种原因,单元格移动到了错误的位置,即使排序本身是正确的。我知道这一点,因为我可以触发一个简单的reloadData()。我的逻辑如下,apples是数据源数组: let sortedApples = apples.sort({$0.tastiness < $1.tastiness}) let sortMap = apples.map({sortedApples.indexOf($

我试图在对数据源数组进行排序时,在UICollectionView中显示移动到位的单元格。我做了以下尝试,由于某种原因,单元格移动到了错误的位置,即使排序本身是正确的。我知道这一点,因为我可以触发一个简单的
reloadData()。我的逻辑如下,
apples
是数据源数组:

let sortedApples = apples.sort({$0.tastiness < $1.tastiness})
let sortMap = apples.map({sortedApples.indexOf($0)!})

self.CollectionView.performBatchUpdates(
{
    for i in 0 ..< sortMap.count
    {
        if i != sortMap[i]
        {
             self.CollectionView.moveItemAtIndexPath(NSIndexPath.init(forItem: i, inSection: 0), toIndexPath: NSIndexPath.init(forItem: sortMap[i], inSection: 0))
        }
    }
},
completion:
{ finished in
    //apples = sortedApples
})
apples = sortedApples //tried this in the completion block too but that also didn't work
let sortedaples=apples.sort({$0.tastyness<$1.tastyness})
让sortMap=apples.map({sortedaples.indexOf($0)!})
self.CollectionView.performbatchUpdate(
{
对于0中的i..
有人能找出我做错了什么吗?或者,如果有另一个可行的解决方案,只要它能适用于可变的单元格高度,它就太有用了


谢谢

你可以试试self.CollectionView.moveItemAtIndexPath(NSIndexPath.init(forItem:sortMap[i],第0节)到indeXPath:NSIndexPath.init(forItem:i,第0节))吗?我想你应该在
CollectionView.PerformButUpdate
之前设置
Apple=sortedApples
@a\tuo是的,这就是问题所在。谢谢优化是可能的吗?如果我有1000个元素。。。那个for循环将阻止我的主UI线程。@Fabiosoft这是一个有趣的问题!由于必须为每个移动单元格调用moveItemAtIndexPath(),而且显然必须在主线程上执行此操作,因此我相信对于循环,您将需要它。优化它的一种方法是预先制作另一个数组或字典,只使用涉及可见单元格的映射,然后循环使用。但是,如果单元格大小可变,或者同时添加或删除项目,这可能不起作用,我的解决方案需要考虑所有这些。您是否找到了更具可扩展性的解决方案?