gpt4 book ai didi

swift - CollectionView 滚动到新插入的项目

转载 作者:行者123 更新时间:2023-11-30 10:48:50 25 4
gpt4 key购买 nike

我有一个由 NSFetchedResultsController 驱动的 CollectionView。

CollectionViewLayout 是按名称升序排列的单元格的水平“轮播”布局。

新项目插入时带有自定义动画。

 func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

if type == NSFetchedResultsChangeType.Insert {
println("Insert Object: \(newIndexPath)")

UIView.animate(withDuration: 1.0, delay: 0.0, options: .curveEaseOut, animations: {
self.collectionView?.insertItems(at: [newIndexPath])
}, completion: { finished in
self.collectionView?.scrollToItem(at: newIndexPath, at: .centeredHorizontally, animated: true)
})
)
...

它可以工作,但动画有点小故障,并且滚动同时发生。

我想滚动到 Item,然后使用自定义动画插入它,但如果我在插入之前滚动到 Item,应用程序就会崩溃。

这里应该做什么?

谢谢

最佳答案

我要尝试的第一件事是将 animate(withDuration:delay:options:animations:completion:) 替换为 performBatchUpdates(_:completion:)

func controller(controller: NSFetchedResultsController,
didChangeObject anObject: AnyObject,
atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath?)
{

if type == NSFetchedResultsChangeType.Insert {
println("Insert Object: \(newIndexPath)")

self.collectionView?.performBatchUpdates({
self.collectionView?.insertItems(at: [newIndexPath])
}, completion: { finished in
self.collectionView?.scrollToItem(at: newIndexPath, at: .centeredHorizontally, animated: true)
})

}

如果这仍然给您带来问题,那么您可以在下一个运行循环中调用滚动。

func controller(controller: NSFetchedResultsController,
didChangeObject anObject: AnyObject,
atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath?)
{

if type == NSFetchedResultsChangeType.Insert {
println("Insert Object: \(newIndexPath)")

self.collectionView?.performBatchUpdates({
self.collectionView?.insertItems(at: [newIndexPath])
}, completion: { finished in
DispatchQueue.main.async { // Defer to next runlop.
self.collectionView?.scrollToItem(at: newIndexPath, at: .centeredHorizontally, animated: true)
}
})

}

最后,您可以尝试仅对滚动部分进行动画处理。

func controller(controller: NSFetchedResultsController,
didChangeObject anObject: AnyObject,
atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath?)
{

if type == NSFetchedResultsChangeType.Insert {
println("Insert Object: \(newIndexPath)")

self.collectionView?.reloadItems(at: [newIndexPath]) // reload without animating.

DispatchQueue.main.async { // Defer to next runlop.
self.collectionView?.scrollToItem(at: newIndexPath, at: .centeredHorizontally, animated: true)
}

}

关于swift - CollectionView 滚动到新插入的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55104787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com