SwiftUI macOS 命令(菜单栏)和视图

Ter*_*nso 9 macos menubar swift swiftui

大家好,我开始学习 SwiftUI 和 macOS 开发。我正在使用 SwiftUI 生命周期。如何从菜单栏的聚焦窗口调用函数。

除了 Apple 文档之外,我还找到了此参考,并且能够使用命令创建菜单项,但我不知道如何从我的角度调用函数。

例如:

假设这是我的应用程序结构:

import SwiftUI

@main
struct ExampleApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }.commands {
        CommandMenu("First menu") {
            Button("Action!") {
                // How do I call the views action function?
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的观点:

struct ContentView: View {
    public func action() {
        print("It works")
    }
    var body: some View {
        Text("Example")
    }
}
Run Code Online (Sandbox Code Playgroud)

我刚刚输入了示例代码,如果有任何拼写错误,抱歉,但我希望您能明白。

jn_*_*pdx 12

由于ViewSwiftUI 中的 s 是瞬态的,因此您无法保存对特定实例的引用ContentView来调用其上的函数。不过,您可以做的是更改传递到内容视图的部分状态。

例如:

@main
struct ExampleApp: App {
    @StateObject var appState = AppState()
    
    var body: some Scene {
        WindowGroup {
            ContentView(appState: appState)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
        }.commands {
            CommandMenu("First menu") {
                Button("Action!") {
                    appState.textToDisplay = "\(Date())"
                }
            }
        }
    }
}

class AppState : ObservableObject {
    @Published var textToDisplay = "(not clicked yet)"
}

struct ContentView: View {
    @ObservedObject var appState : AppState
    
    var body: some View {
        Text(appState.textToDisplay)
    }
}

Run Code Online (Sandbox Code Playgroud)

注意.commands修改器继续WindowGroup { }

在此示例中,AppStateObservableObject保存应用程序某些状态的 。它被传递到ContentView使用参数。您还可以通过环境对象传递它(https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data- Between-views )

单击菜单项时,它会设置的textToDisplay属性。每当更新 @Published 属性时都会更新。@PublishedAppStateContentViewAppState

这是您要使用的模式的总体思路。如果您有此模式未涵盖的用例,请在评论中告诉我。

根据您的评论进行更新

import SwiftUI
import Combine

@main
struct ExampleApp: App {
    @StateObject var appState = AppState()
    
    var body: some Scene {
        WindowGroup {
            ContentView(appState: appState)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
        }.commands {
            CommandMenu("First menu") {
                Button("Action!") {
                    appState.textToDisplay = "\(Date())"
                }
                Button("Change background color") {
                    appState.contentBackgroundColor = Color.green
                }
                Button("Toggle view") {
                    appState.viewShown.toggle()
                }
                Button("CustomCopy") {
                    appState.customCopy.send()
                }
            }
        }
    }
}

class AppState : ObservableObject {
    @Published var textToDisplay = "(not clicked yet)"
    @Published var contentBackgroundColor = Color.clear
    @Published var viewShown = true
    
    var customCopy = PassthroughSubject<Void,Never>()
}

class ViewModel : ObservableObject {
    @Published var text = "The text I have here"
    var cancellable : AnyCancellable?

    func connect(withAppState appState: AppState) {
        cancellable = appState.customCopy.sink(receiveValue: { _ in
            print("Do custom copy based on my state: \(self.text) or call a function")
        })
    }
}

struct ContentView: View {
    @ObservedObject var appState : AppState
    @State var text = "The text I have here"
    @StateObject private var viewModel = ViewModel()
    
    var body: some View {
        VStack {
            Text(appState.textToDisplay)
                .background(appState.contentBackgroundColor)
            if appState.viewShown {
                Text("Shown?")
            }
        }
        .onReceive(appState.$textToDisplay) { (newText) in
            print("Got new text: \(newText)")
        }
        .onAppear {
            viewModel.connect(withAppState: appState)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的更新中,您可以看到我已经解决了背景颜色、显示隐藏视图的问题,甚至onReceive在 @Published 属性之一发生更改时收到通知(通过 )。

您还可以看到我如何使用自定义发布者 ( ) 将操作customCopy传递给 的ContentViewViewModel