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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.