我试图查看用户是否在表视图中按下单元格,但我无法将其与nil进行比较?如果没有按下手机,我该如何检查?这是用户长按表视图时的处理程序

func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
    let p: CGPoint = gestureRecognizer.locationInView(self.tableView)
    let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(p)!
    if indexPath == nil{

    }
    else if gestureRecognizer.state == .Began {
        print(indexPath.row)
    }

}

最佳答案

您不应强制展开,然后检查是否存在会导致应用程序崩溃的nil。你应该做的是:放下打开的包装,然后比较!

func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
    let point = gestureRecognizer.locationInView(self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(point)
    if let touchedPath = indexPath {
        if gestureRecognizer.state == .Began {
            print(touchedPath.row)
        }
    }
}

10-08 05:23