SwiftUI,从场景更改视图(:继续
SwiftUI, changing a view from scene(:continue
在SwiftUI
应用中,我面临着新的挑战,希望有人能给我一些提示或指导。到目前为止,我所看到的在应用程序各部分之间进行通信的机制似乎不太适合这里。但这可能是由于我对 SwiftUI
.
的经验仍然有限
首先是相关代码:
class SceneDelegate {
... lot of code irrelevant to the question ...
func scene(_ scene: UIScene,
continue userActivity: NSUserActivity) {
... useful things happening for the app ...
// Now the view should change ... by some mechanism.
// This is the point of the question.
}
}
和:
struct ContentView: View {
... lot of code irrelevant to the question ...
var body: some View {
VStack {
... code to draw the view ...
}
... more code to draw the view ...
}
}
其次,我的问题是:在 scene(:continue ?
我想到了一些想法,在 scene(:continue 函数中做一些事情,这会影响视图的绘制。
不幸的是,在尝试实现时,我意识到绘制视图的代码是在 scene(:continue 函数之前执行的。因此我需要一些其他机制(通知,绑定喜欢,或 ??) 重绘视图。
是否有好的做法或标准方法?
在这种情况下使用EnvironmentObject
比较合适
class AppState: ObservableObject
@Published var someVar: Sometype
}
class SceneDelegate {
let appState = AppState()
func scene(_ scene: UIScene,
continue userActivity: NSUserActivity) {
// ... other code
appState.someVar = ... // modify
}
}
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// .. other code
let contentView = ContentView()
.environmentObject(appState)
//
}
}
struct ContentView: View {
@EnvironmentObject var appState
var body: some View {
VStack {
// ... other code
appState.someVar // use here as needed
}
}
}
在SwiftUI
应用中,我面临着新的挑战,希望有人能给我一些提示或指导。到目前为止,我所看到的在应用程序各部分之间进行通信的机制似乎不太适合这里。但这可能是由于我对 SwiftUI
.
首先是相关代码:
class SceneDelegate {
... lot of code irrelevant to the question ...
func scene(_ scene: UIScene,
continue userActivity: NSUserActivity) {
... useful things happening for the app ...
// Now the view should change ... by some mechanism.
// This is the point of the question.
}
}
和:
struct ContentView: View {
... lot of code irrelevant to the question ...
var body: some View {
VStack {
... code to draw the view ...
}
... more code to draw the view ...
}
}
其次,我的问题是:在 scene(:continue ?
我想到了一些想法,在 scene(:continue 函数中做一些事情,这会影响视图的绘制。
不幸的是,在尝试实现时,我意识到绘制视图的代码是在 scene(:continue 函数之前执行的。因此我需要一些其他机制(通知,绑定喜欢,或 ??) 重绘视图。
是否有好的做法或标准方法?
在这种情况下使用EnvironmentObject
比较合适
class AppState: ObservableObject
@Published var someVar: Sometype
}
class SceneDelegate {
let appState = AppState()
func scene(_ scene: UIScene,
continue userActivity: NSUserActivity) {
// ... other code
appState.someVar = ... // modify
}
}
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// .. other code
let contentView = ContentView()
.environmentObject(appState)
//
}
}
struct ContentView: View {
@EnvironmentObject var appState
var body: some View {
VStack {
// ... other code
appState.someVar // use here as needed
}
}
}