我创建了UserData的实例,以便其他类可以观察该实例并使用用户名显示必要的信息。我要在这里做的是,当用户登录时,将根据应用程序中的用户活动不时更新(即通过调用api)具有与用户相关的存储属性的不同类。 但是,它在属性初始值设定项中显示错误“无法使用实例成员'userData'”。属性初始化程序在“自我”可用之前运行。任何想法如何解决这个问题? 我不确定如何将数据从单个ObservedObject传递到另一个。
struct passingData: View {
@ObservedObject var userData = UserData()
@ObservedObject var images = ImageURL(userData: userData)
@ObservedObject var payment = Payment(userData: userData)
var body: some View {
VStack{
TextField("Enter userName", text: $userData.userName)
Text("url is \(images.imageURL)")
Text("Payment detail: \(payment.paymentDate)")
}
}
}
class Payment: ObservableObject{
@Published var paymentDate = ""
@ObservedObject var userData: UserData
init(userData: UserData){
self.userData = userData
loadPaymentDate()
}
func loadPaymentDate(){
self.paymentDate = "last payment date from \(userData.userName) is someDate "
}
}
class ImageURL: ObservableObject{
@Published var imageURL = ""
@ObservedObject var userData: UserData
init(userData: UserData){
self.userData = userData
loadImageURL()
}
func loadImageURL(){
self.imageURL = "123_\(userData.userName).com"
}
}
class UserData: ObservableObject{
@Published var userName = ""
}
答案 0 :(得分:1)
这是可能的解决方案:
struct passingData: View {
@ObservedObject var userData: UserData
@ObservedObject var images: ImageURL
@ObservedObject var payment: Payment
init() {
let data = UserData()
self.userData = data
self.images = ImageURL(userData: data)
self.payment = Payment(userData: data)
}
// ... other code