Home > Net >  SwiftUI List selection doesn’t show If I add a NavigationLink and a .contextMenu to the list. Is thi
SwiftUI List selection doesn’t show If I add a NavigationLink and a .contextMenu to the list. Is thi

Time:01-07

List selection doesn’t show If I add a NavigationLink and a .contextMenu to the list, when I select a row, the selection disappears.

struct ContentView: View {
    @State private var selection: String?
    let names = ["Cyril", "Lana", "Mallory", "Sterling"]
    var body: some View {
        NavigationView {
            List(names, id: \.self, selection: $selection) { name in
                NavigationLink(destination: Text("Hello, world!")) {
                    Text(name)
                        .contextMenu {
                            Button(action: {}) {
                                Text("Tap me!")
                            }
                        }
                }
            }
            .toolbar {
                EditButton()
            }
        }
    }
}

CodePudding user response:

We can disable context menu button(s) for the moment of construction in edit mode (because the button is a reason of issue).

Here is a possible approach - some redesign is required to handle editMode inside context menu (see also comments inline).

Tested with Xcode 13.2 / iOS 15.2

demo

struct ContentViewSelection: View {
    @State private var selection: String?
    let names = ["Cyril", "Lana", "Mallory", "Sterling"]

    var body: some View {
        NavigationView {
            List(names, id: \.self, selection: $selection) { name in
                // separated view is needed to use editMode
                // environment value
                NameCell(name: name)
            }
            .toolbar {
                EditButton()
            }
        }
    }
}

struct NameCell: View {
    @Environment(\.editMode) var editMode     // << !!
    let name: String

    var body: some View {
        NavigationLink(destination: Text("Hello, world!")) {
            Text(name)
        }
        .contextMenu {
            if editMode?.wrappedValue == .inactive {    // << !!
                Button(action: {}) {
                    Text("Tap me!")
                }
            }
        }
    }
}
  •  Tags:  
  • Related