UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to pass a variable backwards and forward between views?

Forums > Swift

The title isn't very clear but this is what I want to do:

ForEach(tortoises.items, id: \.name){ item in
                                VStack{
                                    Text("Name: \(item.name)")
                                        .font(.title)
                                    Text("Age: \(item.age)")
                                        .font(.title)
                                    NavigationLink("Change Age"){
                                        AgeChange(age: item.age) 

                                    }

I want to change item.age using this picker in a different view

Here is the view:


struct AgeChange: View{
    @State var age: Int
    var body: some View{
        Picker("Age:", selection: $age){
            ForEach(0..<120){
                Text("Age: \($0)")
                    .font(.title)

            }
        }
    }
}

2      

This is because in your AgeChange you declared age as @State. Basically, it means, that your age variable is owned by this view. Which is not. You need a Binding.

https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-binding-property-wrapper

I changed your variable name just to create my own examples.

NavigationView {
    List($myTortoises, id: \.name) { $item in
    VStack{
        Text(item.name)
        .font(.title)
      Text("Age: \(item.age)")
          .font(.title)
            NavigationLink("Change Age"){
        AgeChange(age: $item.age)                
            }
        }
    }
}
struct AgeChange: View{
    @Binding var age: Int

    var body: some View{
    Picker("Age:", selection: $age){
        ForEach(0..<120){
        Text("Age: \($0)")
            .font(.title)
      }
    }
  }
}

2      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.