Displaying a List with SwiftUI from a remote JSON file
显示来自远程 JSON 文件的 SwiftUI 列表
The purpose of this tutorial is to show a simple way to fetch data from a remote JSON file and display it on a List in SwiftUI. Apple has a tutorial with a local file, also this one teaches you how to do this, however I want to show a simpler way using a newer version of Xcode 11.0 (11A420a).
本教程的目的是展示一种从远程 JSON 文件中获取数据并将其显示在 SwiftUI 的 List 中的简单方法。 苹果有一个本地文件的教程,也教你如何做到这一点,但我想显示一个更简单的方式使用新版本的 Xcode 11.0(11A420a)。
Apple beta libraries are getting constantly changed before releasing the final versions, so older tutorials might not work on the latest versions of XCode
在发布最终版本之前,苹果的测试版本库会不断更新,所以以前的教程可能无法在最新版本的 XCode 上工作
Supposing we have this JSON file, that show an array of movie titles.
假设我们有这个 JSON 文件,它显示一组电影标题。
1 | [ |
And we want to display them on a SwiftUI List like this.
我们希望像这样在 SwiftUI 列表中显示它们。
First we need to define the model for Movie in this case a struct with Decodable and Identifiable protocols. Decodable to be able to decode it from the JSON file and Identifiable to be able to be listed with List. List allows you to display a list of data from an Identifiable Collection just like a UITableViewController.
首先,在这种情况下,我们需要为 Movie 定义一个具有可解码和可识别协议的结构。 可解码能够从 JSON 文件解码,可识别能够与列表一起列出。 List 允许您像 UITableViewController 一样显示可识别集合中的数据列表。
1 | struct Movie: Decodable, Identifiable { |