首页 > 解决方案 > 3D Touch:UICollectionViewCell 中的 registerForPreviewing

问题描述

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

任何帮助将不胜感激。

谢谢

标签: iosswiftuicollectionviewcell3dtouch

解决方案


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

}

输出:

在此处输入图像描述


推荐阅读