3D Touch:在 UICollectionViewCell 中注册预览

3D Touch: registerForPreviewing in UICollectionViewCell

这里的场景是,UICollectionView 在 UITableViewCell 中,UITableView 在 UIViewController 中,现在我必须使用 UILongPressGestureRecognizer如果 3D Touch 不可用我需要在 UICollectionView Cell 中注册它,UILongPressGestureRecognizer工作正常,但我无法在 3D Touch 的单元格中注册 registerForPreviewing。在cell.

中注册这个的方法是什么

我们将不胜感激。

谢谢

3D Touch 只能在 UIViewControllerinstance of UIViewController class

上注册

现在,您必须使用 3D Touch 注册您的 tableView。唯一的问题是选择 UITableViewCell 中的 UICollectionViewCell。

您可以在 UIViewControllerPreviewingDelegate 委托方法中获得它

func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {

    //Get indexPath for selected tableViewCell using location
    guard let tableViewIndexPath = tableView.indexPathForRow(at: location) else {
        return nil
    }

    //Get selected tableViewCell
    //NestedCell is UITableViewCell
    guard let tableViewCell = tableView.cellForRow(at: tableViewIndexPath) as? NestedCell else {
        return nil
    }

    //CollectionView which is in every tableViewCell
    let collectionView = tableViewCell.collectionView

    //Get the location of collectionView
    let collectionViewLocation = tableView.convert(location, to: collectionView)

    //Get indexPath of selected collectionViewCell
    guard let collectionViewIndexPath = collectionView.indexPathForItem(at: collectionViewLocation) else {
        return nil
    }

    //Finally, you get selected collectionViewCell
    guard let collectionViewCell = tableViewCell.collectionView.cellForItem(at: collectionViewIndexPath) else {
        return nil
    }

    let preview = PreviewVC()
    preview.view.backgroundColor = collectionViewCell.backgroundColor
    preview.preferredContentSize = CGSize(width: 0.0, height: 600)

    //Modify CGRect/frame for selected collectionview cell
    var sourceRect = collectionViewCell.frame
    sourceRect.origin.x = sourceRect.origin.x - collectionView.contentOffset.x

    let y = tableViewCell.frame.origin.y + collectionViewCell.frame.origin.y
    sourceRect.origin.y = y
    previewingContext.sourceRect = sourceRect
    return preview

}

输出: