我似乎无法让这个工作,我试图在uicollectionview上植入长按手势 在SO中发现此代码,现在我只需将其转换为swift,所以我可以使用它探测
obj-c
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
return;
}
CGPoint p = [gestureRecognizer locationInView:self.collectionView];
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:p];
if (indexPath == nil){
NSLog(@"couldn't find index path");
} else {
// get the cell at indexPath (the one you long pressed)
UICollectionViewCell* cell =
[self.collectionView cellForItemAtIndexPath:indexPath];
// do stuff with the cell
}
}
我的快速方法
func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer){
if (gestureRecognizer.state != UIGestureRecognizerState.Ended){
return
}
let p: CGPoint = gestureRecognizer.locationInView(self.collectionView)
let indexPath: NSIndexPath = self.collectionView.indexPathForItemAtPoint(p)!
if (indexPath == nil) { // Error here 'NSIndexPath' is not convertible to 'UIGestureRecognizerState'
println("couldn't find index path")
} else {
let cell: UICollectionViewCell = self.collectionView.cellForItemAtIndexPath(indexPath)
}
}
感谢任何帮助,它失败了if(indexPath == nil)错误' NSIndexPath'不能转换为' UIGestureRecognizerState'
答案 0 :(得分:1)
尝试使用可选绑定来确定optional
是否包含值。 indexPathForItemAtPoint
返回一个可选值。
if let indexPath = self.collectionView.indexPathForItemAtPoint(p)
{
let cell: UICollectionViewCell = self.collectionView.cellForItemAtIndexPath(indexPath)
}
else
{
println("couldn't find index path")
}
答案 1 :(得分:0)
您还可以使用可选链接并映射可选的索引路径。
let cell = collectionView.indexPathForItemAtPoint(p).map {
self.collectionView.cellForItemAtIndexPath($0)
}
if let cell = cell {
// Do something with non-optional cell
} else {
println("No cell for point")
}
单元格变量是UICollectionViewCell吗? (可选)但这仍然是cellForItemAtIndexPath
调用的返回类型。
如果您可以继续或返回可选单元格,则可以跳过整个if let
部分,尤其是在您不需要打印错误时(或if cell == nil { println("No cell for point") }
有关处理选项的更多方法,请参阅此博文:How I Handle Optionals In Swift