如何导航到SwiftUI结构并按id显示



所以我设法将来自服务器的图像和文本显示到ContentView 中

struct ContentView: View {
init() {
Webservice().getAllPosts {
print($0)
}
}
@ObservedObject var model = PostListViewModel()
var body: some View {
List(model.posts) { post in
VStack{
Text("Title: ").bold()
+ Text("(post.title)")
ImageView(withURL: "http://localhost:8000/(post.path.replacingOccurrences(of: " ", with: "%20"))")
Text("Description: ").bold()
+ Text("(post.description)")

}
}
}
}

而我得到的数据看起来是这样的:

[Test.Post(id: "9ffb2c83-45ed-4198-b6ab-9a259ef91b44", title: "The burbz", path: "public/1584106997200-astronomy-space-abstract-galaxy.jpg", description: "theone23"), Test.Post(id: "922f6ffc-8738-4bc2-a96d-654678540f5a", title: "Test", path: "public/1584045867007-71188186_249463072641040_8764351972645011456_n.jpg", description: "PLus that"), Test.Post(id: "45ef0279-6179-43b3-8a45-7a0fb4acefd5", title: "The burbz", path: "public/1584040897839-smiley.png", description: "OCtober"), Test.Post(id: "fa3d34ed-325b-479e-8b8f-c59831f0790d", title: "The burbz", path: "public/1584040654626-home-icon.jpg", description: "theone23"), Test.Post(id: "7c35e1ee-28e0-4845-bd14-dcad27025b04", title: "The burbz", path: "public/1584039156755-add.png", description: "theon23"), Test.Post(id: "f1567e48-eb24-4ccc-b24d-6c7c9c99e326", title: "dff", path: "public/1584038265741-Profile-img-icon.png", description: "YETT"),...

以下是我获取数据的方法:

从我的url 获取数据

class Webservice {
func getAllPosts(completion: @escaping ([Post]) -> ()) {
guard let url = URL(string: "http://localhost:8000/albums")
else {
fatalError("URL is not correct!")
}
URLSession.shared.dataTask(with: url) { data, _, _ in
let posts = try!
JSONDecoder().decode([Post].self, from: data!); DispatchQueue.main.async {
completion(posts)
}
}.resume()
}
}

变量

struct Post: Codable, Hashable, Identifiable {
let id: String
let title: String
let path: String
let description: String
}

将变量设置为完成后的帖子(帖子(

final class PostListViewModel: ObservableObject {
init() {
fetchPosts()
}
@Published var posts = [Post]()
private func fetchPosts() {
Webservice().getAllPosts {
self.posts = $0
}
}

}

我的问题是如何点击id列表中的项目,或者我可以做什么来导航到id列表中并查看每个项目,并按id显示所有内容。

我在这里了解了苹果公司关于如何使用导航构建列表的信息:https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation它奏效了。谢谢苹果。

最新更新