1

I'm trying use context menu with UIViewRepresentable. When context menu is activated, UIViewRepresentable disappears.

Here is the code:

UIViewRepresentable view:

struct TestView: UIViewRepresentable {
    func makeUIView(context: Context) -> some UIView {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
        view.backgroundColor = UIColor.red
        return view
    }
    func updateUIView(_ uiView: UIViewType, context: Context) {
        //
    }
}

ContentView:

struct ContentView: View {
    var body: some View {
        TestView()
            .frame(width: 200, height: 200)
            .contextMenu {
                Text("Context Menu")
            }
    }
}

How to make UIViewRepresentable not disappear?

2 Answers2

4

I ran into this same issue and found that the clipped() modifier works fine on iOS 15.0 and later. But it doesn't fix the problem on iOS 14.

As I was experimenting with different approaches I discovered that the compositingGroup() fixes the problem on iOS 14.0 and later including iOS 15.

struct ContentView: View {
    var body: some View {
        TestView()
            .frame(width: 200, height: 200)
            .compositingGroup()
            .contextMenu {
                Text("Context Menu")
            }
    }
}

UIViewRepresentable rendered correctly within a contextMenu

a7md
  • 123
  • 1
  • 7
  • This also works with TextField. Without `compositingGroup()`, the text will disappear when being long pressed. – heshuimu Mar 13 '23 at 00:38
3

I ran into this exact issue recently with my UIViewRepresentable view that returns a custom UIImageView. The fix was adding a clipped() modifier to the view with the context menu. Not sure if this applies to your case though as mine involved an image.

This was tested on iPhone 12 Pro running iOS 15.1.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Thanks! you saved our day with a similar issue. When a view representable was added and removed it wouldn't appear.... Any idea why that is? – Kugutsumen Mar 24 '22 at 15:08
  • Just for the google index: UIViewRepresentable also vanishes when `.doDrag(....)`and `clipped()` also helps when dragging. – Gerd Castan Jul 25 '23 at 18:31