Search code examples
swiftuicontextmenuswiftui-navigationlinkios14xcode12

NavigationLink in ContextMenu no longer working in iOS14 xcode12 beta3?


Wondering if anyone else has this issue, and if a workaround has been found. This works fine in iOS 13, but seems broken in iOS 14. I am just trying to fire off a NavigationLink to another View, from a .contextMenu.

My code is as below.

import SwiftUI

struct ContentView: View {
    var body: some View {
        
        NavigationView {
            VStack {
                HStack {
                    Text("I am a text in a HStack ")
                }
                HStack {
                    NavigationLink(destination: TestView()) {
                        VStack {
                            Image(systemName:"gauge")
                                .font(.system(size: 31))
                        }
                    }
                }
            }
            .contextMenu {
                NavigationLink(destination: TestView()) {
                    Text("Navigate to TestView")
                    Image(systemName: "pencil")
                }
            }
        }
    }
}

The Destination TestView() is just a boilerplate "Hello World" view.

If I click not the Icon associated in the Stack, this triggers the navigation perfectly. But the same link in the context menu does not. When I select it in the contextmenu, nothing happens. I.e I can select the menu item, but all it does is close the context menu and I stay on the same view.

Anyone else found this? solved it ? Thanks


Solution

  • Here is a demo of possible approach. Tested with Xcode 12b3 / iOS 14 (also valid for SwiftUI 1.0)

    struct ContentView: View {
        @State private var showLink = false
    
        var body: some View {
    
            NavigationView {
                VStack {
                    HStack {
                        Text("I am a text in a HStack ")
                    }
                    HStack {
                        NavigationLink(destination: Text("TestView")) {
                            VStack {
                                Image(systemName:"gauge")
                                    .font(.system(size: 31))
                            }
                        }
                    }
                }
                .background(NavigationLink("", destination: Text("TestView"), isActive: $showLink))
                .contextMenu {
                    Button(action: { self.showLink = true }) {
                        HStack {
                            Text("Navigate to TestView")
                            Image(systemName: "pencil")
                        }
                    }
                }
            }
        }
    }