集合视图(创建可拖动的UICollectionViewCell)致命错误

时间:2016-09-27 13:04:52

标签: ios swift uicollectionview uicollectionviewcell

我正在尝试为集合视图中的单元格提供拖放功能。类似于下面的那个,除了这个是一个简单的UIView: https://www.cocoacontrols.com/controls/lgdragdrop

为了将它扩展到Collection View,我依靠这个整洁的小黑客 https://adoptioncurve.net/archives/2014/07/creating-a-draggable-uicollectionviewcell/

这是黑客攻击 “将单元格内容的副本创建为图像,然后将其拖动到手指下方的屏幕上。”

我已将代码转换为Swift:

func handlePan(panRecognizer: UIPanGestureRecognizer){
    var locationPoint: CGPoint! = panRecognizer.locationInView(self.collectionView)

    //var locationPoint: CGPoint = panRecognizer.locationInView(self.collectionView)

    if panRecognizer.state == .Began {
        print("Pan Gesture BEGAN")

        var indexPathOfMovingCell: NSIndexPath = self.collectionView.indexPathForItemAtPoint(locationPoint)!
        var cell: UICollectionViewCell = self.collectionView.cellForItemAtIndexPath(indexPathOfMovingCell)!
        UIGraphicsBeginImageContext(cell.bounds.size)
        cell.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        var cellImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.movingCell = UIImageView(image: cellImage)
        //self.movingCell.userInteractionEnabled = true
        self.movingCell.center = locationPoint
        self.movingCell.alpha = 0.75
        self.collectionView.addSubview(self.movingCell)
    }
    if panRecognizer.state == .Changed {
        print("Pan Gesture CHANGED")

        self.movingCell.center = locationPoint
    }
    if panRecognizer.state == .Ended {
        print("Pan Gesture ENDED")

        self.movingCell.removeFromSuperview()
    }

}`

然而,我收到错误

Pan Gesture BEGAN
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

在以下一行

self.movingCell.center = locationPoint

还有其他与“展开可选值”相关的帖子,但在我的具体案例中没有帮助我

请帮忙......

另外,我不确定是否可以将单元格拖到集合视图之外。如果没有,需要为此添加什么代码。

1 个答案:

答案 0 :(得分:0)

看起来你强行展开这两个:

var indexPathOfMovingCell: NSIndexPath = self.collectionView.indexPathForItemAtPoint(locationPoint)!
var cell: UICollectionViewCell = self.collectionView.cellForItemAtIndexPath(indexPathOfMovingCell)!

你不应该这样做,因为手指的位置当前可能不在任何单元格上,这将返回零。相反,你应该做什么让那些作为选项。并安全地解开它们:

var indexPathOfMovingCell: NSIndexPath? = self.collectionView.indexPathForItemAtPoint(locationPoint)

if let indexPath = indexPathOfMovingCell {

    if let cell = self.collectionView.cellForItemAtIndexPath(indexPath) {
        UIGraphicsBeginImageContext(cell.bounds.size)
        cell.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        var cellImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        // Rest of your code
        ...
    }
}

希望有所帮助:)

我根据Swift中的教程撰写了一篇文章,它还包含一些改进,例如将单元格拖到集合视图之外。您可以查看here