Because View
SwiftUI 中的 s 是瞬态的,您无法保存对特定实例的引用ContentView
调用它的函数。你什么can不过,要做的是更改传递到内容视图的部分状态。
例如:
@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)
}
}
请注意,.commands
修改器继续WindowGroup { }
在这个例子中,AppState
is an ObservableObject
保存应用程序的某些状态。它已经传递到ContentView
使用参数。您还可以通过环境对象传递它(https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data- Between-views https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views)
单击菜单项时,它会设置textToDisplay
这是一个@Published
属性于AppState
. ContentView
每当 @Published 属性时都会更新AppState
得到更新。
这是您将使用的模式的总体思路。如果您有此模式未涵盖的用例,请在评论中告诉我。
根据您的评论进行更新:
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)
}
}
}
在我的更新中,您可以看到我已经解决了背景颜色的问题,显示隐藏视图,甚至收到通知(通过onReceive
) 当 @Published 属性之一发生更改时。
您还可以查看我如何使用自定义发布者(customCopy
) 将动作传递给ContentView
's ViewModel