GuardianKnight
GuardianKnight

Reputation: 63

How to change @State value in SwiftUI?

I have a user data saved in UserDefaults, now I want to make an edit profile view and I want to use TextField to show current user data, but I get this error because I put the code inside the body Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols. I want to display all current user data inside the TextField, so they can see their data before make an edit. how to do that correctly?

MyCode

struct EditProfile: View {
    
    @AppStorage(CurrentUserDefaults.EMAIL) var currentUserEmail: String?
    @AppStorage(CurrentUserDefaults.USERNAME) var currentUserName: String?
    
    @State var userName = ""
    @State var userPhone = ""
    @State var userAddress = ""
    
    var body: some View {
        username = currentUserName ?? "" //[Error] I want to display currentUserName on the textfield
        NavigationView{
            VStack{
                TextField("Username", text: $userName)
            }.navigationBarTitle("Edit Profile")
        }.navigationViewStyle(StackNavigationViewStyle())
    }
}

Upvotes: 0

Views: 4193

Answers (1)

jnpdx
jnpdx

Reputation: 52312

If you're looking to set userName to the @AppStorage value and then change a temporary @State variable (maybe to be committed later), you could use onAppear to set it:

NavigationView{
            VStack{
                TextField("Username", text: $userName)
            }
            .navigationBarTitle("Edit Profile")
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .onAppear {
            userName = currentUserName ?? ""
        }

You can't do inline code like the variable assignment you're trying to do inside a View's body because it's a special type of computed property (or function) called a ViewBuilder where the contents get automatically returned: https://developer.apple.com/documentation/swiftui/viewbuilder

Upvotes: 2

Related Questions