SwiftUI JSON sẽ không in tiêu đề trong ScrollView HStack (nhưng sẽ trong Danh sách)

Aug 17 2020

Tôi gặp lỗi trong tệp ContentView.swift của mình và khi đang cố gắng tìm hiểu, tôi không hiểu lỗi đang nói gì.

Tôi hiểu rằng nó không thể gán giá trị của loại Chương trình cho loại Bài đăng nhưng tôi muốn lấy tiêu đề như thế nào?

Làm cách nào tôi có thể lấy nó để in trong 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()
    }
}

Ngoài ra, điều này hoạt động nhưng nó không thể cuộn được.

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

để rõ ràng kết quả cuối cùng tôi đang cố gắng nhận được là thế này.

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

Trả lời

RajatMishra Aug 18 2020 at 09:31

Hãy dọn dẹp và xây dựng dự án. Mã có vẻ hoạt động tốt. Tôi đã tạo một dự án mới và chỉ cần sao chép & dán đoạn mã trên mà bạn đã viết và nó đang hoạt động bình thường.

ĐÃ CHỈNH SỬA - Để hiển thị danh sách theo chiều ngang, vui lòng sử dụng mã dưới đây:

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