2

Say you have a context menu for an image that pops up when long pressed. How can you make the popup larger, but keep the same dimension?


ViewControllerTableViewCell: UITableViewCell, UIContextMenuInteractionDelegate {

func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
    UIContextMenuConfiguration(identifier: nil, previewProvider: nil)  { _ in
        let share = UIAction(title: "", image: UIImage(systemName: "")) { _ in
            // share code
        }
        return UIMenu(title: "", children: [share])
    }
}

override func awakeFromNib() {
    super.awakeFromNib()
    immy.isUserInteractionEnabled = true
    immy.addInteraction(UIContextMenuInteraction(delegate: self))
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
uuuuuu
  • 119
  • 1
  • 7

1 Answers1

6

You can provide your own previewProvider to your context menu. Just create a custom view controller with an image view for previewing the image at the desired size:

import UIKit

class ImagePreviewController: UIViewController {
    private let imageView = UIImageView()
    init(image: UIImage) {
        super.init(nibName: nil, bundle: nil)
        preferredContentSize = image.size
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.image = image
        view = imageView
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

Then just add the custom preview provider implementation to the UIContextMenuConfiguration initializer:

func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
    UIContextMenuConfiguration(identifier: nil) {
        ImagePreviewController(image: self.immy.image!)
    } actionProvider: { _ in
        let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { _ in
           // share code
        }
        return UIMenu(title: "Profile Picture Menu", children: [share])
    }        
}

edit/update:

Without any action

func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
    UIContextMenuConfiguration(identifier: nil, previewProvider:  {
        ImagePreviewController(image: self.immy.image!)
    })
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/218009/discussion-on-answer-by-leo-dabus-change-popup-size-of-uiimage-in-contextmenu). – Samuel Liew Jul 17 '20 at 06:33