SwiftUI contextMenu on material background darkens the content when activated

Viewed 294

I'm using material background in SwiftUI (introduced with iOS 15). When applied to a view that also has a contextMenu modifier when the context menu is shown it darkens the whole content. To make sure it's not related to my project I created an example project and it has the same issue.

Code:

struct ContentView: View {
    var body: some View {
        ZStack {
            Color(.systemBlue).ignoresSafeArea()
            Text("Press for Context Menu")
                .padding()
                .background(.regularMaterial)
                .contextMenu {
                    Button("Option 1", action: {})
                    Button("Option 2", action: {})
                    Button("Option 3", action: {})
                }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
//            .preferredColorScheme(.dark)
    }
}

Here is the result: activated context menu darkens the content when material background is used

Interestingly it works correctly in dark mode: activated context menu works as expected in dark mode when material background is used

2 Answers

The order of modifiers matters. To avoid this darkening, simply swap the modifiers, so that the .contextMenu is applied before the .background:

                Text("Press for Context Menu")
                    .padding()
                    .contextMenu {
                        Button("Option 1", action: {})
                        Button("Option 2", action: {})
                        Button("Option 3", action: {})
                    }
                    .background(.regularMaterial)

It should look like this:

context menu with material

Add the background with the material after the contextMenu modifier. You're still gonna get a weird appearance when opening the contextual menu though, cause another material is applied on top of it.

Related