如何使用SwiftUI绑定ObservableObject的发布者

flvlnr44  于 2023-02-15  发布在  Swift
关注(0)|答案(1)|浏览(184)

我不知道如何在视图文件的ObservableObject类中绑定Publisher。
用户

struct User: Identifiable,Decodable{
    var id: String?
    var email: String
    var username: String
    
}

视图模型

class UserProfileViewModel: ObservableObject{
   @Published var user: User?

   //fetch data and bind the user property
}

用户配置文件

struct UserProfile: View {  
    @ObservedObject private var userProfileVM = UserProfileViewModel()
     var body: some View {
        VStack{
       UserForm(name: Binding($userProfileVM.user.username)!, 
               email: Binding($userProfileVM.user.email)!
            )               }
     }
}

用户表单

struct UserForm: View {
    @Binding var name: String
    @Binding var email: String
    
    var body: some View {
        TextField("name", text: $name)
                    .keyboardType(.namePhonePad)
        TextField("email", text: $email)
    }
}

我不知道如何在UserForm上绑定UserProfile中的userProfileVM.user.usernameuserProfileVM.user.email,现在我在UserProfile中得到错误Value of optional type 'User?' must be unwrapped to refer to member 'email' of wrapped base type 'User' & Chain the optional using '?' to access member 'email' only for non-'nil' base values
请告诉我如何解决。

8i9zcol2

8i9zcol21#

一般来说,如果你使用的是!,就会有一些不正确的地方。这应该是非常罕见的。
您需要检查@Published var user: User?是否不是nil

struct UserProfile: View {
    //StateObject is for initializing ObservedObject is for passng around.
    @StateObject private var userProfileVM = UserProfileViewModel()
     var body: some View {
        VStack{
            if let userB = Binding($userProfileVM.user){
                //Check if there is a user.
                UserForm(name: userB.username,  email: userB.email)
            }else{
                //Show/do something if there isn't
                ProgressView()
                    .task{
                        //Load user somehow...
                    }
            }
        }
     }
}

相关问题