'contextMenuInteraction on UIButton

What I want to do:

I have a UITableViewCell with 4 UIButtons. I want to be able to long press on any one of the buttons and peek display a ViewController with different data based on which button was interacted with.

What I have tried:

@available(iOS 13.0, *)
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {

    let location = interaction.location(in: tableView)
    guard let indexPath = tableView.indexPathForRow(at: location) else {
        return nil
    }

    guard let cell = tableView.cellForRow(at: indexPath) else {
        return nil
    }

    guard let button = cell.hitTest(location, with: nil) as? UIButton else {
        return nil
    }

    let stuff : [String : Any] = ["tag" : button.tag as NSNumber, "indexPath" : indexPath as IndexPath]

    let config = UIContextMenuConfiguration(identifier: stuff as NSCopying) { () -> UIViewController? in
        return ProfitSpreadsheetViewController()
    }

    return config

}

@available(iOS 13.0, *)
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, previewForHighlightingMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {

    guard let stuff = configuration.identifier as? [String : Any] else {
        return nil
    }

    if let tag = stuff["tag"] as? Int {

        guard let cell = tableView.cellForRow(at: stuff["indexPath"] as! IndexPath) else {
            return nil
        }

        if let button = cell.viewWithTag(tag) {
            return UITargetedPreview(view: button)
        }
    }

    return nil
}

What isn't working:

No subviews of the UITableViewCell are responding to a long press and none of the delegate methods are called. I tried an alternate version of this code where I use the tableView context menu delegate methods, but that only worked when I long pressed on the actual cell, and not any of its subviews (such as a UIButton), which is what led me to this approach.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source