Swift:在切换视图后使用UILongPressGestureRecognizer时应用程序崩溃

时间:2017-12-23 01:51:06

标签: swift view crash switch-statement gesture

在我看来,我已经包含了两个不同的UIGestureRecognizer,UILongPressGestureRecognizer和UITapGestureRecognizer。一个用于重新排列我的UICollectionView图像,另一个用于简单点击,导致所选图像的详细视图。

一切正常,但是一旦我在呈现详细的图像视图后返回视图,每当我尝试拖动图像时应用程序都会崩溃。点击功能每次都有效,但是在开始拖动图像后立即发生崩溃。

override func viewDidLoad() {
    super.viewDidLoad()

    self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
    self.longPressGesture.delegate = self

    self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTapGesture(gesture:)))
    self.tapGesture.delegate = self

    collectionView?.addGestureRecognizer(self.longPressGesture)
    collectionView?.addGestureRecognizer(self.tapGesture)
}

我的点按功能:

@objc func handleTapGesture(gesture: UITapGestureRecognizer) {
    self.performSegue(withIdentifier: "displayImage", sender: self)
}

我的长按功能:

@objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
    switch(gesture.state) {
    case .began:
        print("begin hold!")
        guard let selectedIndexPath = self.collectionView?.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
            break
        }
        self.collectionView?.beginInteractiveMovementForItem(at: selectedIndexPath)
    case .changed:
        print("change hold!")
        self.collectionView?.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
    case .ended:
        print("end hold!")
        UIView.performWithoutAnimation {
            self.collectionView?.endInteractiveMovement()
        }
    default:
        print("cancel hold!")
        self.collectionView?.cancelInteractiveMovement()
    }
}

崩溃时,我得到了

  

libc ++ abi.dylib:以未捕获的类型异常终止   NSException

这似乎发生在func handleLongGesture()中嵌入的.changed-case中。

有什么想法吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

在经历了几个小时的挣扎之后,我终于找到了造成这个问题的原因。它与手势无关,但与集合视图及其数据无关。在viewWillAppear()中,我通过将缩略图重新添加到数组来更新视图:

self.thumbnails.removeAll()
    for i in 0 ..< self.images.count {
        ... adding new (updating) thumbnails ...
}

但出于某种原因,我忘了调用thumbnails.removeAll(),导致数据被复制而不在集合视图上调用reloadData(),导致它崩溃。

相关问题