SwiftUI JSON จะไม่พิมพ์ชื่อเรื่องใน ScrollView HStack (แต่จะอยู่ในรายการ)
Aug 17 2020
ฉันได้รับข้อผิดพลาดในไฟล์ ContentView.swift ของฉันและในขณะที่ฉันพยายามเรียนรู้ว่าฉันไม่เข้าใจว่าข้อผิดพลาดนั้นพูดถึงอะไร
ฉันเข้าใจว่ามันไม่สามารถกำหนดค่าของประเภทโปรแกรมให้กับประเภทโพสต์ได้ แต่ฉันจะได้รับชื่ออย่างไร?
ฉันจะนำสิ่งนี้ไปพิมพ์ใน 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()
}
}
นอกจากนี้ยังใช้งานได้ แต่ไม่สามารถเลื่อนได้
ForEach(posts){ post in
HStack {Text(post.title)}
}.onAppear{
Api().getPosts { (posts) in
self.posts = posts
}
}
เพื่อให้ชัดเจนผลลัพธ์สุดท้ายที่ฉันพยายามได้คือสิ่งนี้
ScrollView(.horizontal) {
HStack(spacing: 20) {
ForEach(0..<10) {
Text("Item \($0)")
.foregroundColor(.white)
.font(.largeTitle)
.frame(width: 200, height: 200)
.background(Color.red)
}
}
}
คำตอบ
RajatMishra Aug 18 2020 at 09:31
กรุณาทำความสะอาดและสร้างโครงการ ดูเหมือนว่าโค้ดจะทำงานได้ดี ฉันได้สร้างโครงการใหม่และเพียงแค่คัดลอกและวางโค้ดด้านบนที่คุณเขียนและมันทำงานได้อย่างถูกต้อง
แก้ไข - หากต้องการแสดงรายการในแนวนอนโปรดใช้รหัสด้านล่าง:
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"))
}