1

Looks like there's a problem when using the .contextMenu view modifier with nested views.

Here's sample code showing the problem:

import SwiftUI

enum SampleEnum: String, CaseIterable {
  case one, two, three, four
}

struct ContentView: View {
  var body: some View {
    Form {
      Section {
        VStack  {
          HStack  {
            ForEach(SampleEnum.allCases, id:\.self) { id in
              Text(id.rawValue)
                .contextMenu {
                  Button {
                    print("Change country setting")
                  } label: {
                    Label("Choose Country", systemImage: "globe")
                  }
                }
            }
          }
        }
      }
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

Here's the result: enter image description here

So, it doesn't appear that a context menu can be performed on a single Text view since the entire section/stack is selected.

Is there any way to get the contextMenu to work on an individual Text view in such a nested layout?

4
  • Likely to do with the form. Try a Vstack and see if there is a difference Commented Nov 1, 2021 at 12:45
  • .contextMenu is deprecated Commented Nov 1, 2021 at 19:28
  • 1
    @eXCore Only the version of .contextMenu that takes a ContextMenu value is deprecated. Commented Feb 16, 2022 at 11:51
  • @LukeRedpath Yeah, my bad, sorry. Commented Mar 20, 2022 at 15:42

1 Answer 1

4

Try this workaround, I changed contextMenu to Menu() and passed your Text() as its param, made each text has its own menu as you wanted and prints each ID correctly as a proof that each action is independent to each Text()

Code:

struct ContentView: View {
    var body: some View {
        Form {
            Section {
                VStack  {
                    HStack  {
                        ForEach(SampleEnum.allCases, id:\.self) { id in
                            Menu("\(Text(id.rawValue))") {
                                Button {
                                    print("Change country setting")
                                    print(id)
                                } label: {
                                    Label("Choose Country", systemImage: "globe")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Recording

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! My example was a simpler version of what my app needs but a simple test in the actual app looks promising.
@Phantom59 glad it helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.