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

前端 未结 2 1967
伪装坚强ぢ
伪装坚强ぢ 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

    0 讨论(0)
  • 2021-01-24 23:25

    Your CityModel and TownModel need to conform to Identifiable, just add an id to them like you did in UserModel.

    Than you need to edit your UserList NavigationLink:

    NavigationLink(destination: CityList(cities: user.cities)) {
        Text(user.firstName)
    }
    

    The Navigation is now like this: UserList -> CityList -> TownList

    CityList:

    struct CityList: View {
    
        var cities: [CityModel]
    
        var body: some View {
            List (cities) { city in
                NavigationLink(destination: TownList(towns: city.towns)) {
                    Text(city.name)
                }
            }
        }
    }
    

    TownList:

    struct TownList: View {
    
        var towns: [TownModel]
    
        var body: some View {
            List (towns) { town in
                Text(town.name)
            }
        }
    }
    

    I hope that helps, in my test project it works!

    0 讨论(0)
提交回复
热议问题