简体   繁体   中英

How can I pass an object property as binding in swiftui

I have a UserService class with an optional user variable.

struct User: Codable {
    var id, first_name, last_name, dob: String
}

class UserService : ObservableObject {
    @Published var user: User?
}

I pass this object from a view to another view in NavigationLink.

NavigationLink(destination: EditProfileView(userService: userService).navigationBarBackButtonHidden(true), isActive: $editProfileScreenActive){
                    Text("")
                }

In EditProfileView I was not able to use the properties of User in TextField. eg

TextField("first_name", text: $userService.user?.first_name)

I tried different approaches but was not able to pass first_name as a binding to TextField. I am getting different kinds of compilation errors.

Any suggestions how to fix this? (I am not an experienced swift programmer :) )

As the user is optional and TextField expects a non optional String as the text parameter, you have to first check if the user is not nil .

if let user = Binding($userService.user) {
    TextField("first_name", text: user.firstName)
}

However, if you still want to have a text field when the user is nil (this depends on what you are trying to achieve on this screen, I cannot determine this from your question), you might simply want to have an @State variable that you initialise with the users first name.

Check by making a shared let, equal to User . Like this:

struct User: Codable {
    static let shared = User()
    var id, first_name, last_name, dob: String
}

So now you only have to type User.shared.propertyName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM