SwiftUI JSON 不会在 ScrollView HStack 中打印标题(但会在列表中) [英] SwiftUI JSON won't print title in ScrollView HStack (but will in List)
问题描述
我的 ContentView.swift 文件中出现错误,当我尝试学习时,我不明白这些错误在说什么.
I am getting errors in my ContentView.swift file, and as I am trying to learn I am not understanding what the errors are saying.
我知道它无法将 Program 类型的值分配给 Post 类型,但我打算如何获得标题?
I get that it can't assign the value of type Program to the type Post but how am I meant to get the title?
我怎样才能在 HStack 中打印出来?
How can I get this to print in 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()
}
}
这也有效,但不可滚动.
Also this does work but it is not scrollable.
ForEach(posts){ post in
HStack {Text(post.title)}
}.onAppear{
Api().getPosts { (posts) in
self.posts = posts
}
}
要清楚我想要得到的最终结果是这样的.
to be clear the end result I am trying to get is this.
ScrollView(.horizontal) {
HStack(spacing: 20) {
ForEach(0..<10) {
Text("Item \($0)")
.foregroundColor(.white)
.font(.largeTitle)
.frame(width: 200, height: 200)
.background(Color.red)
}
}
}
推荐答案
请清理并构建项目.该代码似乎工作正常.我创建了一个新项目并简单地复制 &粘贴上面你写的代码,它工作正常.
Please clean and build the project. The code seems to work fine. I've created a new project and simply copied & pasted the above code that you've written and it is working correctly.
已编辑 -要水平显示列表,请使用以下代码:
EDITED - To show the list horizontally, please use below code:
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"))
}
这篇关于SwiftUI JSON 不会在 ScrollView HStack 中打印标题(但会在列表中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!