SwiftUI 学习笔记

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

2020-08-10  本文已影响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("菜单")
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读