我有一个非常简单的示例 macOS 应用程序,它带有一个自定义选单命令,只是为了测验我的想法,如下所示。
import SwiftUI
@main
struct MenuMonsterMacApp: App {
@State var fileOpenEnabled: Bool = true
var body: some Scene {
WindowGroup {
ContentView()
.frame(width: 480.0, height: 320.0)
}.commands {
CommandGroup(after: .newItem) {
Button {
print("Open file, will you?")
} label: {
Text("Open...")
}
.keyboardShortcut("O")
.disabled(false)
}
}
}
}
我想通过单击放置在ContentView
. 所以我创建了一个ObservableObject
类来观察 File Open 命令的布林值,如下所示。
import SwiftUI
@main
struct MenuMonsterMacApp: App {
@ObservedObject var menuObservable = MenuObservable()
@State var fileOpenEnabled: Bool = true
var body: some Scene {
WindowGroup {
ContentView()
.frame(width: 480.0, height: 320.0)
}.commands {
CommandGroup(after: .newItem) {
Button {
print("Open file, will you?")
} label: {
Text("Open...")
}
.keyboardShortcut("O")
.disabled(!fileOpenEnabled)
}
}.onChange(of: menuObservable.fileOpen) { newValue in
fileOpenEnabled = newValue
}
}
}
class MenuObservable: ObservableObject {
@Published var fileOpen: Bool = true
}
在我的ContentView
虚拟运行节目中,我有以下内容。
import SwiftUI
struct ContentView: View {
@StateObject var menuObservable = MenuObservable()
var body: some View {
VStack {
Button {
menuObservable.fileOpen.toggle()
} label: {
Text("Click to disable 'File Open'")
}
}
}
}
如果我单击该按钮,相关选单命令的布尔状态将不会改变。这是一个错误的方法吗?如果是,如何启用和禁用选单命令ContentView
?谢谢。
uj5u.com热心网友回复:
要通过单击放置在 中的按钮来启用和禁用命令,请ContentView
尝试以下方法,使用传递environmentObject
和选单按钮的单独视图。
import SwiftUI
@main
struct MenuMonsterMacApp: App {
@StateObject var menuObservable = MenuObservable()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(menuObservable)
.frame(width: 480.0, height: 320.0)
}.commands {
CommandGroup(after: .newItem) {
OpenCommand().environmentObject(menuObservable)
}
}
}
}
struct OpenCommand: View {
@EnvironmentObject var menuObservable: MenuObservable
var body: some View {
Button {
print("Open file, will you?")
} label: {
Text("Open...")
}
.disabled(!menuObservable.fileOpen)
.keyboardShortcut("O")
}
}
class MenuObservable: ObservableObject {
@Published var fileOpen: Bool = true
}
struct ContentView: View {
@EnvironmentObject var menuObservable: MenuObservable
var body: some View {
VStack {
Button {
menuObservable.fileOpen.toggle()
} label: {
Text("Click to disable 'File Open'")
}
}
}
}
0 评论