ios - 如何在 swiftUI 中使用 EnvironmentObject 获取原始对象的价值
问题描述
class GameSettings: ObservableObject {
@Published var score = 0
@Published var score1:Int? = 0
}
struct ScoreView: View {
@EnvironmentObject var settings: GameSettings
var body: some View {
NavigationView {
NavigationLink(destination: ContentView3()) {
Text("Score: \(settings.score)")
}
}
}
}
struct ContentView3: View {
@StateObject var settings = GameSettings()
@EnvironmentObject var settings111: GameSettings
var body: some View {
NavigationView {
VStack {
// A button that writes to the environment settings
Text("Current Score--->\(settings.score))")
Text(settings111.score1 == nil ? "nil" : "\(settings111.score1!)")
Button("Increase Score") {
settings.score += 1
}
NavigationLink(destination: ScoreView()) {
Text("Show Detail View")
}
}
.frame(height: 200)
}
.environmentObject(settings)
}
}
所以在这里当用户在导航路线中执行了一些更改时,ContentView3
如果用户登陆到同一个屏幕ContentView3
,那么我怎样才能获得GameSettings
对象的最新值呢?我尝试创建@EnvironmentObject var settings111: GameSettings
但崩溃。
解决方案
您是否也添加.environmentObject()
到 YourApp.swift 中?
如果没有,您必须像这样添加它
生命周期:SwiftUI
@main
struct YourApp: App {
var settings: GameSettings = GameSettings()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(settings)
}
}
}
生命周期:UIKit
在 SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
var settings: GameSettings = GameSettings() // added line
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(settings))) // added ".environmentObject(settings)" after contentView
self.window = window
window.makeKeyAndVisible()
}
}
预习
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(GameSettings())
}
}
推荐阅读
- angular - 角度和评估:我得到一个环境错误
- javascript - 如何更改选中复选框的父元素的样式
- react-native - 我应该将 onBackPressureBuffer(n) 放在 RxJava 订阅链的哪个位置?
- jquery - jQuery "this" apparently not selecting unique instance
- r - R:根据其他两列的匹配替换列
- sql - 通过 VPN 看不到 SQL 视图,但可以看到表
- mysql - MySQL 错误 - ALTER 在此位置无效
- linux - Ansible 中的全局修改 $PATH 无法在常规 Linux shell 中按预期工作
- vue.js - 如何在 VueJS 中监听一个组件的所有事件?
- java - 不推荐使用 HTTPUtils .. 我该怎么做?