将 Obj-c 转换为 swift,长按手势

converting Obj-c to swift, long press gesture

我似乎无法让它工作,我正在尝试在 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
    }
}

我在 swift

中的方法
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' is not convertible to 'UIGestureRecognizerState'

尝试使用可选绑定来查明optional是否包含一个值。 indexPathForItemAtPoint returns 可选值。

if let indexPath = self.collectionView.indexPathForItemAtPoint(p)
{
    let cell: UICollectionViewCell = self.collectionView.cellForItemAtIndexPath(indexPath)
}
else
{
     println("couldn't find index path")
}

阅读 Apple 的 swift 书中的可选内容。 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309

您还可以使用可选的链接并映射可选的索引路径。

let cell = collectionView.indexPathForItemAtPoint(p).map {
  self.collectionView.cellForItemAtIndexPath([=10=])
}

if let cell = cell {
  // Do something with non-optional cell
} else {
  println("No cell for point")
}

单元格变量将是 UICollectionViewCell? (可选)但那是 cellForItemAtIndexPath 调用的 return 类型。

如果您可以继续或 return 可选单元格,您可以跳过整个 if let 部分,特别是如果您不需要打印错误(或执行 if cell == nil { println("No cell for point") }

有关处理可选值的更多方法,请参阅此博文:How I Handle Optionals In Swift