Home > Software engineering >  How to pass the cell index into the previewProvider of a context menu in swift?
How to pass the cell index into the previewProvider of a context menu in swift?

Time:11-24

I have the following and I am trying to understand how to pass the indexPath.row for the UICollectionViewCell into the previewProvider so that I can preview a larger version of the selected image.

I have an array of larger images that are referenced via the indexPath.row

I have tried changing to makeRatePreview(cellIndex: Int) and passing in the index but this only throws errors.

func collectionView(_ collectionView: UICollectionView,
                                 contextMenuConfigurationForItemAt indexPath: IndexPath,
                                 point: CGPoint) -> UIContextMenuConfiguration? {
        
        return UIContextMenuConfiguration(identifier: nil, previewProvider: makeRatePreview) { suggestedActions in
            
            let inspectAction =
                UIAction(title: NSLocalizedString("InspectTitle", comment: ""),
                         image: UIImage(systemName: "arrow.up.square")) { action in
                }
            
            let deleteAction =
                UIAction(title: NSLocalizedString("DeleteTitle", comment: ""),
                         image: UIImage(systemName: "trash"),
                         attributes: .destructive) { action in
                }
            
            return UIMenu(title: "", children: [inspectAction, deleteAction])
        }
    }
    
    
    // MARK: - Context menu for images
    
    func makeRatePreview() -> UIViewController {
        
      let viewController = UIViewController()
      
      // 1
      let imageView = UIImageView(image: UIImage(named: "rating_star"))
      viewController.view = imageView
      
      // 2
      imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
      imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.backgroundColor = .blue
      
      // 3
      viewController.preferredContentSize = imageView.frame.size
      
      return viewController
    }

CodePudding user response:

UIContextMenuConfiguration's initializer expects UIContextMenuContentPreviewProvider for the previewProvider argument.

In the documentation:

public typealias UIContextMenuContentPreviewProvider = () -> UIViewController?

This means we want to pass in a closure. You could pass in makeRatePreview fine since it is of type () -> UIViewController.

However, when you changed it to makeRatePreview(cellIndex: 0) it is now of type UIViewController, which is incorrect. To fix this, just put it in a closure by adding { ... } around the call:

{ makeRatePreview(cellIndex: 0) }
  • Related