SwiftUI JSON no imprimirá el título en ScrollView HStack (pero lo hará en List)

Aug 17 2020

Recibo errores en mi archivo ContentView.swift y, como intento aprender, no entiendo lo que dicen los errores.

Entiendo que no puede asignar el valor de tipo Programa al tipo Publicación, pero ¿cómo se supone que obtengo el título?

¿Cómo puedo hacer que esto se imprima en HStack?

import SwiftUI
import RemoteImage

struct ContentView: View {
  
    @State var posts: [Program] = []
    
   var body: some View {
    List(posts){ post in
        
        Text("hello")
        
        /*RemoteImage(type: .url(URL(string:post.url)!), errorView: { error in
            Text(error.localizedDescription)
        }, imageView: { image in
            image
            .resizable()
            .aspectRatio(contentMode: .fit)
        }, loadingView: {
            Text("Loading ...")
        })*/
        
        
       // UrlImageView(post.url)
        } .onAppear {
           Api().getPosts { (posts) in
                            self.posts = posts
                           }
                    }
    

    
   
     
        }
}
import SwiftUI

// Add this top level struct to
// decode properly
struct Post: Codable {
    var programs: [Program]
}

struct Program: Codable, Identifiable {
    let id = UUID()
    var title : String
    var icon : String
}

class Api {
    // Update this to return an array of Program
    func getPosts(completion: @escaping ([Program]) -> ()) {
        guard let url = URL(string: "https://api.drn1.com.au/api-access/programs/DRN1") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            // Based on the updated structs, you would no
            // longer be decoding an array
            let post = try! JSONDecoder().decode(Post.self, from: data!)
            DispatchQueue.main.async{
                // The array is stored under programs now
                completion(post.programs)
            }
            
        }
    .resume()
    }
}

También esto funciona pero no es desplazable.

  ForEach(posts){ post in
                  HStack {Text(post.title)}
               }.onAppear{
                   Api().getPosts { (posts) in
                       self.posts = posts
                   }
               }

para que quede claro, el resultado final que estoy tratando de obtener es este.

ScrollView(.horizontal) {
    HStack(spacing: 20) {
        ForEach(0..<10) {
            Text("Item \($0)")
                .foregroundColor(.white)
                .font(.largeTitle)
                .frame(width: 200, height: 200)
                .background(Color.red)
        }
    }
}

Respuestas

RajatMishra Aug 18 2020 at 09:31

Limpie y construya el proyecto. El código parece funcionar bien. Creé un nuevo proyecto y simplemente copié y pegué el código anterior que escribiste y está funcionando correctamente.

EDITADO: para mostrar la lista horizontalmente, utilice el siguiente código:

var body: some View {
    NavigationView {
        if posts.isEmpty {
            Text("Loading")
        } else {
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(alignment: .center, spacing: 10) {
                    ForEach(posts) { post in
                        return Text(post.title)
                    }
                }
            }.frame(height: 200)
        }
    }.onAppear {
        Api().getPosts { (posts) in
            self.posts = posts
        }
    }.navigationBarTitle(Text("Home"))
}