Send data to next view - SwiftUI

Viewed 145

So I have been trying to get a simple pass of data working with SwiftUI.

Basically the below script prints out a list of items (in a HStack) I then have each one linked to our Podcast() view.

What I am trying to do is pass through the podcast name to the next view. How do I achieve this? As all the examples are about int which I am not using am using a String.

import SwiftUI
import RemoteImage

struct ContentView: View {

    @State private var showAlert = false
    @State var posts: [Program] = []

   var body: some View {
        NavigationView {
            if posts.isEmpty {
                Text("Loading")
            } else {
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(alignment: .bottom, spacing: 10) {
                        ForEach(posts) { post in
                            //return
                            NavigationLink(destination: Podcasts()){
                            RemoteImage(type: .url(URL(string:post.icon)!), errorView: { error in
                                Text(error.localizedDescription)
                            }, imageView: { image in
                                image
                                .resizable()
                                .renderingMode(.original)
/*                                .clipShape(Circle())
                                .shadow(radius: 10)
                                .overlay(Circle().stroke(Color.red, lineWidth: 5))*/
                                .aspectRatio(contentMode: .fit)
                                .frame(width:200, height:200)
                            }, loadingView: {
                                Text("Loading ...")
                            })
                            }
                        }
                    }.frame(height: 200)
                }.frame(height: 200)
            }
        }.onAppear {
            Api().getPosts { (posts) in
                self.posts = posts
            }
        }.navigationBarTitle(Text("Home"))
    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The podcast View

import SwiftUI

struct Podcasts: View {
    
 
    var body: some View {
      
        NavigationView{
            Text("Hello")
        }.navigationBarTitle(Text("Podcast"))
    
    }
        
}


struct Podcasts_Previews: PreviewProvider {
    static var previews: some View {
        Podcasts()
    }
}
1 Answers

Pass post as constructor argument, like

ForEach(posts) { post in
    //return
    NavigationLink(destination: Podcasts(post: post)){

so now

struct Podcasts: View {
    let post: Program
 
    var body: some View {

        // !! DON'T ADD SECOND NAVIGATION VIEW IN STACK 
        // !! - THERE MUST BE ONLY ONE

        Text(post.name)
           .navigationBarTitle(Text("Podcast"))
    }
}
Related