简体   繁体   English

SwiftUI 如果我将 NavigationLink 和 a.contextMenu 添加到列表中,则不显示列表选择。 这是一个已知的错误?

[英]SwiftUI List selection doesn’t show If I add a NavigationLink and a .contextMenu to the list. Is this a known bug?

List selection doesn't show If I add a NavigationLink and a.contextMenu to the list, when I select a row, the selection disappears.列表选择不显示如果我将 NavigationLink 和 a.contextMenu 添加到列表中,当我 select 一行时,选择就会消失。

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()
            }
        }
    }
}

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).这是一种可能的方法 - 需要重新设计来处理上下文菜单中的editMode (另请参见内联注释)。

Tested with Xcode 13.2 / iOS 15.2使用 Xcode 13.2 / iOS 15.2 测试

演示

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!")
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM