gpt4 book ai didi

ios - Collection View (创建可拖动的 UICollectionViewCell) fatal error

转载 作者:行者123 更新时间:2023-11-30 13:02:53 27 4
gpt4 key购买 nike

我正在尝试在 Collection View 中获取单元格的拖放功能。与下面的类似,只不过这是一个简单的 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

还有其他与“展开可选值”相关的帖子,但对我的具体情况没有帮助

请帮忙...

此外,我不确定是否可以将单元格拖动到 Collection View 之外。如果没有,需要添加什么代码。

最佳答案

看起来您正在强制解开这两个:

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 教程写了一篇文章,它还包含一些改进,例如将单元格拖到 Collection View 之外。你可以去看看here .

关于ios - Collection View (创建可拖动的 UICollectionViewCell) fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725456/

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