美文网首页SwiftUI 学习笔记
用Json文件数据建立列表页面

用Json文件数据建立列表页面

作者: 艾迪不是奥特曼 | 来源:发表于2020-08-10 20:16 被阅读0次
image.png

以下是实现代码

image.png

设置 Model 数据的结构体

struct MenuSection: Codable, Identifiable {
    var id: UUID
    var name: String
    var items: [MenuItem]
}

struct MenuItem: Codable, Equatable, Identifiable {
    var id: UUID
    var name: String
    var photoCredit: String
    var price: Int
    var restrictions: [String]
    var description: String
    
    var mainImage: String {
        name.replacingOccurrences(of: " ", with: "-").lowercased()
    }
    

代码:

struct ContentView: View {
    let menu = Bundle.main.decode([MenuSection].self, from: "menu.json")
    
    var body: some View {
        NavigationView {
            List{
                ForEach(menu) { section in
                    Section (header: Text(section.name)) {
                        ForEach(section.items) { item in
                            Text(item.name)
                        }
                    }
                }
            }
            .listStyle(GroupedListStyle())
            .navigationTitle("菜单")
        }
    }
}

相关文章

网友评论

    本文标题:用Json文件数据建立列表页面

    本文链接:https://www.haomeiwen.com/subject/tyqsdktx.html