2

使用isActive动态NavigationLinks 的 bool 数据结构来启用程序化弹回是行不通的。在 中点击Pop BackDestination应该将视图弹出回 root DynamicList,但它不起作用。

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