gpt4 book ai didi

ios - SwiftUI,从场景中改变 View (:continue

转载 作者:行者123 更新时间:2023-12-01 19:30:04 26 4
gpt4 key购买 nike

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 ...
}
}
其次,我的问题是: 在场景内部执行处理后,如何让我的 View 重绘自身(:继续?
我有一些想法,在场景中做一些事情(:继续功能会影响 View 的绘制。
不幸的是,在尝试实现时,我意识到绘制 View 的代码是在场景(:继续函数)之前执行的。因此我需要一些其他机制(如通知、绑定(bind)或??)来重绘 View 。
有没有好的做法或标准的方法来做到这一点?

最佳答案

最好使用 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
}
}
}

关于ios - SwiftUI,从场景中改变 View (:continue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63406009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com