Creating a series of master detail lists from a single JSON file in SwiftUI

前端 未结 2 1972
伪装坚强ぢ
伪装坚强ぢ 2021-01-24 22:40

I\'m trying to work through understanding how I can make data flow nicely through an app I\'m building. I just want a basic master detail view where it starts with a list of all

2条回答
  •  不知归路
    2021-01-24 23:18

    first you have to create CityListView and CityRow, like you did for users:

    struct CityListView: View {
        var user: UserModel
        var body: some View {
    
                // don't forget to make CityModel Identifiable 
                List(user.cities) { city in
                    CityRowView(city: city)
                }
                .navigationBarTitle(Text("Cities"))
            }
        }
    }
    
    struct CityRowView: View {
        var city: CityModel
        var body: some View {
            HStack {
                Text(city. name)
                    .font(.headline)
                Spacer()
            }
        }
    }
    
    

    after that you need to change destination in NavigationLink (not UserRow, but new CityListView)

    ...
    //NavigationLink(destination: UserRow(user: user)) {
    NavigationLink(destination: CityListView(user: user)) {
        UserRow(user: user)
    }
    ...
    

    Another way is to declare variable "cities" as an array of CityModel and receive it from user:

    struct CityListView: View {
        var cities: [UserModel]
        // list for array of cities
    }
    
    // in UserList
    NavigationLink(destination: CityListView(cities: user.cities)) {
        UserRow(user: user)
    }
    

    P.S. Apple made excellent tutorial for navigations in SwiftUI: https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation

提交回复
热议问题