我有一个UICollectionView,我在UICollectionView的单元格中处理Long Press,但我不知道哪个单元格被按下了。我试图在didSelectItemAtIndexPath中捕获单元格indexPath但是没有工作。任何人都可以帮助我? 谢谢!
这是我正在处理LongPress的方法
@IBAction func handleLongPress(sender: AnyObject) {
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context = appDelegate.managedObjectContext!
//here I want to get the item to delete
// var itemToDelete =
//context.deleteObject(itemToDelete)
//context.save(nil)
if sender.state == UIGestureRecognizerState.Began {
let alertController = UIAlertController(title: nil, message: "My message", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "YES", style: .Default, handler: { (action: UIAlertAction!) in
self.numberOfCells = self.numberOfCells - 1
self.myCollectionView.reloadData()
}))
alertController.addAction(UIAlertAction(title: "NO", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: {
println("completion")
})
}
}
答案 0 :(得分:0)
您可以使用其view
属性获取手势识别器操作方法中长按的单元格。然后,您可以使用该视图通过集合视图方法indexPath
获取indexPathForCell:
。
答案 1 :(得分:0)
这里没有足够的信息来回答你的问题。
在我的回答中,我假设每个单元格都有自己的UILongPressGestureRecognizer
。
@IBAction func cellLongPressWithRecognizer(recognizer: UILongPressGestureRecognizer)
{
assert(recognizer.view is UICollectionViewCell)
let cell = recognizer.view as UICollectionViewCell
// Yay, you have the cell!
if let indexPathFromCell = self.collectionView.indexPathForCell(cell) {
// Yay, you have the index path from the cell
}
…
}
如果由于某种原因,您没有将recognizer.view
设置为单元格,您仍然可以使其工作。
@IBAction func cellLongPressWithRecognizer(recognizer: UILongPressGestureRecognizer)
{
let point = recognizer.locationInView(self.collectionView)
if let indexPathFormPoint = self.collectionView.indexPathForItemAtPoint(point) {
// Yay, you have the index path from the touch point
}
…
}