【问题标题】:Problem with .disable modifier in ContextMenu SwiftUIContextMenu SwiftUI 中 .disable 修饰符的问题
【发布时间】:2021-12-31 03:09:28
【问题描述】:

我在我的程序中发现了有趣的动作:

struct Test: View {
    @State private var redButton: Bool = false
    
    var body: some View {
        
        List {
            
            ForEach(1...10, id: \.self) { numbers in

                Button {
                        redButton = false
                } label: {
                    Text("Button \(numbers)")
                }.contextMenu {
                    Button {
                        //action code
                            redButton = true
                    } label: {
                        Text("Deactivate")
                    }.disabled(redButton)
                    
            }
            }
        }
    }
}

如果您运行此代码并在 contexMenu 中按“停用”,contexMenu 将仅对 6..10 按钮禁用,此代码会随机关闭/打开 contextMenu 元素(尝试增加或减少列表元素并按“停用”随机列表元素)。 如果 U 删除 List all 使用一个按钮正常工作。 更改 redButton 状态时,也许我需要使用 dispatchQueue.main.async ? 我做错了什么?

【问题讨论】:

  • 你能解释一下你到底想达到什么目标吗?
  • 如果你在上下文菜单中选择红色,每行都有“优先状态”(红色、黄色、绿色),之后你不能再次选择该行的红色状态(上下文菜单红色禁用)
  • 我很抱歉,但这似乎是错误的 contextMenu,因为我使用 Menu 而不是 contextMenu 并且它工作正常。

标签: swiftui swiftui-list


【解决方案1】:

正确代码:

struct Test: View {
    @State var redButton: Bool = false
    
    var body: some View {
        
        List {
            
            ForEach(1...3, id: \.self) { numbers in
                
                    Menu("Actions \(numbers)") {
                        Button("Deactivate", action: {
                            redButton = true
                        })
                        Button("Activate", action: {
                            redButton = false
                        })
                        Button(action: {}) {
                            
                            Label("Delete", systemImage: "trash")
                            
                        }.disabled(redButton)
                        Button(action: {}) {
                           
                            Label("Call", systemImage: "phone")
                            
                        }.disabled(redButton)
                    }

            }
        }
    }
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2019-12-29
  • 2021-01-06
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多