NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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)

            }
        }
    }
}

   

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)
      }
    }
  }
}

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

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

Reply to this topic…

You need to create an account or log in to reply.

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.