菜单未更新(SwiftUI 错误?) [英] Menu not updating (SwiftUI bug?)
问题描述
我正在使用 macOS Montery Beta 4 和 Xcode 13 Beta 4,我想我在 SwiftUI
中发现了一个错误.
I'm using macOS Montery Beta 4 along with Xcode 13 Beta 4, and I think I've discovered a bug in SwiftUI
.
当使用 CommandGroup
以及根据条件启用/禁用的按钮时,CommandGroup
不会更新.CommandMenu
但是.
When using a CommandGroup
along with a button that is enabled/disabled based on a condition, the CommandGroup
doesn't update. CommandMenu
does however.
- 创建一个新的 SwiftUI macOS 项目
- 将以下代码粘贴到
App
文件中:
class Test: ObservableObject {
@Published var num = 0
}
@main
struct TestApp: App {
@StateObject private var test = Test()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(test)
}
.commands {
CommandGroup(after: .newItem) {
Button(action: {}) {
Text("Test menu item")
}
.disabled(test.num == 0)
}
}
}
}
- 将以下代码粘贴到
ContentView
文件中:
struct ContentView: View {
@EnvironmentObject var test: Test
var body: some View {
Button(action: {
test.num += 1
}) {
Text(String(test.num) + " ---------")
}
}
}
- 运行应用程序,然后单击
File
菜单.您应该看到测试菜单项"已按预期禁用. - 点击按钮.这只是将数字加 1.但是,测试菜单项"会增加 1.仍然被禁用,即使
test.num
!= 0.
- Run the app, and click on the
File
menu. You should see that "Test menu item" is disabled as expected. - Click on the button. This simply increments a number by 1. However, "Test menu item" is still disabled, even though
test.num
!= 0.
问题是,将 CommandGroup
替换为 CommandMenu("Test menu")
修复了它.
The thing is, replacing the CommandGroup
with CommandMenu("Test menu")
fixes it.
该应用程序所做的只是有一个菜单项,如果数字为零,则该菜单项将被禁用.按下按钮使该数字不为零,但菜单项保持禁用状态.
All the app does is have a menu item that is disabled if a number is zero. Pressing the button makes that number not zero, but the menu item stays disabled.
有人能重现这个吗,这是我的错误吗?
Is anybody able to reproduce this, and is this a bug on my part?
推荐答案
@George_E 答案的一个小变化,是这样的:
a minor variation of @George_E answer, is this:
CommandGroup(after: .newItem) {
TestView(test: test)
}
struct TestView: View {
@ObservedObject var test: Test
var body: some View {
Button(action: {}) {
Text("Test menu item")
}
.disabled(test.num == 0)
}
}
这篇关于菜单未更新(SwiftUI 错误?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!