UICollection视图重新排序单元格崩溃ios swift

时间:2017-07-11 10:57:51

标签: ios swift uipangesturerecognizer

我想重新排序我的uicollection视图的单元格。当我尝试时,它有时会工作(有滞后)但有时,我的应用程序崩溃了。 我在互联网上到处搜索,但直到现在都无法找到答案。

func handleLongGesture(panRecognizer: UIPanGestureRecognizer){

    let locationPoint: CGPoint! = panRecognizer.locationInView(collectionView)
    guard let selectedIndexPath : NSIndexPath = collectionView.indexPathForItemAtPoint(locationPoint) else {
        return
    }
    if panRecognizer.state == .Began{

        collectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)
        indexPathSelectedItem = selectedIndexPath
    }
    else if panRecognizer.state == .Changed{

        collectionView.updateInteractiveMovementTargetPosition(locationPoint)

    }
    else if panRecognizer.state == .Ended{

        collectionView.endInteractiveMovement()
    }
}

这是我正在尝试的上述代码。我无法在整个代码中找到错误。 我想告诉你,我也尝试使用断点来找出我的应用程序崩溃的位置,我发现有时控制无法进入状态“panRecognizer.state == .Ended”,我认为这就是我的原因应用程序崩溃。

1 个答案:

答案 0 :(得分:0)

如果没有崩溃日志,很难确切地说出发生了什么,但同时提出了一些建议:

<强>首先

您在方法的顶部有一个漂亮的警卫声明,我建议您添加let locationPoint: CGPoint! = panRecognizer.locationInView(collectionView)。这样您就不必强行打开包装,代码将受到保护,免受此特定崩溃的影响。

<强>第二

当您调用集合视图的endInteractiveMovement()方法时,它将依次调用您的委托方法collectionView:moveItemAtIndexPath:toIndexPath:,让您现在需要更新数据源并将项目移动到那里。

确保您已实施并将相关对象移动到正确的位置!如果没有,您的应用程序将崩溃,因为数据源不再与集合视图同步。

<强>第三

我建议您使用switch语句而不是if-else来捕获所有其他可能的状态,这将使您可以取消移动操作(您现在没有这样做):

switch(panRecognizer.state) {

    case UIGestureRecognizerState.Began:
        // Begin movement
        collectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)
    indexPathSelectedItem = selectedIndexPath

    case UIGestureRecognizerState.Changed:
        // Update movement
        collectionView.updateInteractiveMovementTargetPosition(locationPoint)

    case UIGestureRecognizerState.Ended:
        // End movement
        collectionView.endInteractiveMovement()

    default:
        collectionView.cancelInteractiveMovement()
    }

}

相关问题