2

Let's say I have the following two Views:

ContentView:

struct ContentView: View {
@State var firstName = "John"
@State var middleName = "Michael"
@State var lastName = "Doe"
var body: some View {
    TabView(){
        ProfileScreen(firstName: $firstName, middleName: $middleName, lastName: $lastName)
            .tabItem {
                Image("Profile")
            }.tag(0)
        HomeScreen()
            .tabItem {
                Image("Home")
            }.tag(1)     
    }
}}

and ProfileScreen:

struct ProfileScreen: View {
@Binding var firstName: String
@Binding var middleName: String
@Binding var lastName: String
var body: some View {
    VStack {
        Text(firstName)
        Text(middleName)
        Text(lastName)
    }
}}

Is there a way for me to contain all three variables (firstName, middleName, and lastName) inside another variable (let's call it userInfo), in order to save space and time so I don't have to bind three separate variables across separate Views?

1 Answer 1

3

You can just wrap all properties in one struct, like below

struct ContentView: View {
    @State var userInfo = UserInfo(firstName: "John", middleName: "Michael", lastName: "Doe")
    
    var body: some View {
        TabView(){
            ProfileScreen(userInfo: $userInfo)
                .tabItem {
                    Image("Profile")
                }.tag(0)
        HomeScreen()
            .tabItem {
                Image("Home")
            }.tag(1)
        }
    }
}

struct UserInfo {
    var firstName: String
    var middleName: String
    var lastName: String
}

struct ProfileScreen: View {
    @Binding var userInfo: UserInfo
    
    var body: some View {
        VStack {
            Text(userInfo.firstName)
            Text(userInfo.middleName)
            Text(userInfo.lastName)
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.