gpt4 book ai didi

ios - @EnvironmentObject 可以与不是 View 的普通结构一起使用吗?

转载 作者:行者123 更新时间:2023-12-01 19:29:49 24 4
gpt4 key购买 nike

我在将类信息从一个结构实例传递到另一个结构实例时遇到了麻烦,所以我一直在尝试解决问题。

这是可行的,因为我正在通过 View

// phone_testingApp.swift
import SwiftUI

@main
struct phone_testingApp: App {

@ObservedObject var myObservedObject = MyObservedObject()

var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(myObservedObject)
}
}
}
// ContentView.swift

import SwiftUI
import Combine

struct ContentView: View {

var subtract = MinusToObject()
@EnvironmentObject var myNumber: MyObservedObject

var body: some View {
VStack{

Text("The number is \(myNumber.theObservedObjectToPass)")

MinusToObject()
.environmentObject(myNumber)
}
}
}

class MyObservedObject: ObservableObject {
@Published var theObservedObjectToPass = 5
}

struct MinusToObject: View {

@EnvironmentObject var theObservedObject: MyObservedObject

var body: some View {
Text("Minus")
.onTapGesture {
theObservedObject.theObservedObjectToPass -= 1
}
}
}

但是如果我只使用一个不符合 View 的普通结构来尝试类似的事情

import SwiftUI
import Combine

struct ContentView: View {

var subtract = MinusToObject()
@EnvironmentObject var myNumber: MyObservedObject

var body: some View {
VStack{

Text("The number is \(myNumber.theObservedObjectToPass)")

Text("Minus")
.onTapGesture {
subtract.subtractIt()
}
}
}
}

class MyObservedObject: ObservableObject {
@Published var theObservedObjectToPass = 5
}

struct MinusToObject {

@EnvironmentObject var theObservedObject: MyObservedObject


func subtractIt() {
theObservedObject.theObservedObjectToPass -= 1 //Thread 1: Fatal error: No ObservableObject of type MyObservedObject found. A View.environmentObject(_:) for MyObservedObject may be missing as an ancestor of this view.
}
}

我收到一个运行时错误,这是我在调用函数时添加的注释。

我对如何传递引用类型的实例感到很困惑,所以我确信我做错了很多事情,我们将不胜感激。

最佳答案

这是行不通的,因为 EnvironmentObject 注入(inject)是在 SwiftUI View 层次结构上执行的,仅针对所有基于 View 的子对象。

如果您希望任何旧对象访问共享实例,您必须手动创建一个单例并将其注入(inject)到 SwiftUI View 层次结构中。

class MyObservedObject: ObservableObject {
static let shared = MyObservedObject()
private init() { }

@Published var theObservedObjectToPass = 5
}

/// you can use it in a plain object
struct MinusToObject {
func subtractIt() {
MyObservedObject.shared.theObservedObjectToPass -= 1
}
}

// you can use it in a view
struct ContentView: View {
var body: some View {
SomeOtherView()
.environmentObject(MyObservedObject.shared)
}
}

关于ios - @EnvironmentObject 可以与不是 View 的普通结构一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63586299/

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