2

isActiveプログラムによるポップバックを有効にするために動的 s の bools にデータ構造を使用してNavigationLinkも機能しません。でポップバックをタップすると、ビューがルートにポップバックされるはずですが、機能しません。DestinationDynamicList

import SwiftUI


struct DynamicList: View {
    @ObservedObject  var listViewModel = ListViewModel()
    
    var body: some View {
        NavigationView {
            List {
                ForEach(0..<self.listViewModel.cities.count, id: \.self) { index in
                    
                    NavigationLink(
                        destination: Destination(isActive: $listViewModel.isActiveItems[index], city: $listViewModel.cities[index]),
                        isActive: $listViewModel.isActiveItems[index],
                        label: {
                            Text(listViewModel.cities[index])
                        })
                }
            }
            .navigationBarTitle(Text("Locations"))
            .navigationBarItems(trailing: Button(action: {
                self.addRow()
            }) {
                Image(systemName: "plus")
            })
        }
    }

    private func addRow() {
        self.listViewModel.addCity(city: ["New York", "London", "Moskau", "Sydney"].randomElement() ?? "")
    }
}

class ListViewModel: ObservableObject {

    @Published var cities: [String] = []
    @Published var isActiveItems: [Bool] = []

    func addCity(city: String){
        cities.append(city)
        isActiveItems.append(false)
    }
}


struct Destination: View {
    @Binding var isActive: Bool
    @Binding var city: String
    var body: some View {
        Text(city)
        Button(action: {
            isActive.toggle()
        }, label: {
            Text("Pop Back")
        })
    }
}

struct DynamicList_Previews: PreviewProvider {
    static var previews: some View {
        DynamicList()
    }
}
4

0 に答える 0