我遇到了错误
严重错误:找不到类型为LoginResponse的ObservableObject。作为该视图的祖先,可能缺少用于LoginResponse的View.environmentObject(_:)。
我已将环境对象传递给LoginView()的所有子视图,但错误仍然存在
struct LoginView: View {
@State var loginCredentials = Credentials()
var loginResponse = LoginResponse()
var dataCall = DataCall()
var body: some View {
VStack{
Button(action:{self.dataCall.AttemptLogin(loginCredentials: self.loginCredentials)}){
Text("LOGIN")
}
Text("\(self.loginResponse.jwt)")
}
.environmentObject(self.loginResponse)
.padding(.horizontal)
}
}
如果需要,这里是其余的代码
struct Credentials: Encodable {
var login: String = ""
var password: String = ""
}
class LoginResponse: Decodable, ObservableObject {
enum CodingKeys: CodingKey {
case success, userId, jwt
}
@Published var success: Bool = false
@Published var userId: String = ""
var error: String = ""
@Published var jwt: String = ""
init(){}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
success = try values.decode(Bool.self, forKey: .success)
userId = try values.decode(String.self, forKey: .userId)
jwt = try values.decode(String.self, forKey: .jwt)
}
}
struct DataCall {
@EnvironmentObject var dataResponse : LoginResponse
func AttemptLogin(loginCredentials: Credentials) {
let loginResponse = LoginResponse()
dataResponse.success = loginResponse.success
}
}
答案 0 :(得分:0)
由于DataCall
不是SwiftUI视图,因此我认为您不能使用.environmentObject
修饰符将数据传递给它。相反,只需在LoginResponse
结构中添加对DataCall
对象的引用,然后像普通一样将其传递给构造函数即可。
示例:
struct DataCall {
weak var dataResponse : LoginResponse
...
}
let dataCall = DataCall(dataResponse: loginResponse)
但是,我对您的视图设计感到非常困惑。您在视图中正常声明的任何对象,如果没有@State
或@ObservedObject
,将一遍又一遍地创建。那是你想要的吗?