Context menu does not show over a SpriteView in SwiftUI

446 views Asked by At

I'm unable to show a context menu over a SpriteView in SwiftUI on a mac. I am able to show a context menu not over it -- right click on the blue works, on red doesn't, see image.

However, I also need to be able to pan the scene in the view, so mouseDragged() inside the scene must work. Placing an overlay() on top of the view blocks mouse dragging events from propagating down to the scene.

Xcode 13.2, deployment 12.2, Swift 5

import SwiftUI
import SpriteView

func MenuItem(_ text: String, _ action: @escaping ()->Void) -> some View {
    Button {
        action()
    } label: {
        Text(text)
    }
}

var scene : SKScene {
    
    let r = SKScene.init(size: CGSize(width: 500, height: 500))

    r.isUserInteractionEnabled = false
    r.scaleMode = .aspectFill
    r.backgroundColor = .red
    
    return r
}

struct ContentView: View {
    var body: some View {
        ZStack {
            SpriteView.init(scene: scene)
                .padding()
                .contextMenu {
                    MenuItem("1 Preferences ...") {
                    }
                }

        }
        .background(Color.blue)
        .contextMenu {
            MenuItem("0 Preferences ...") {
            }
        }
    }
}

enter image description here

1

There are 1 answers

4
Asperi On

A possible solution is to add transparent overlay and attach context menu there, like

SpriteView.init(scene: scene)
    .padding()
    .overlay(
        Color.clear
            .contentShape(Rectangle())
            .contextMenu {               // << here !!
                MenuItem("1 Preferences ...") {
                }
            }
    )

Tested with Xcode 13.4 / macOS 12.5

demo