Home > Back-end >  SwiftUI navigationLink isActivie not working
SwiftUI navigationLink isActivie not working

Time:04-19

My view hierarchy here is view1 -> view2 -> view3.

I use NavigationLink in view1 to open view2 and use Binding to pass a value to isActivie, then pass this value to view3, and when view3 is done, change the value passed to false and close view3 automatically.

But the result is that it stays in view2. Then the value passed in is equal to false

My intention is to come back from view3 and return directly to view1

Here is my code.


// view 1 
@State private var detailViewIsShow: Bool = false

var body some: View {
    ForEach(boughtItems) { item in
            NavigationLink(
                destination: ItemDetailView(item: item, detailViewIsShow: $detailViewIsShow),
                isActive: $detailViewIsShow
            ) {
                ItemCellView(item: item)
            }
            .isDetailLink(false)
        }
}

// view 2
@Binding var detailViewIsShow: Bool
@State var itemEditorViewIsShow: Bool = false

var body: some View {
        ZStack(alignment: .bottom) {
            NavigationLink(
                destination: ItemEditorView(item: item, detailViewIsShow: $detailViewIsShow),
                isActive: self.$itemEditorViewIsShow
            ) {
                EmptyView()
            }
            .isDetailLink(false)
        }
        .padding(.horizontal, 16)
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(true)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {
                    self.itemEditorViewIsShow = true
                }, label: {
                    Image(systemName: "square.and.pencil")
                        .frame(width: 24, height: 24)
                })
            }
        }
    }

// view 3
@Binding var detailViewIsShow: Bool

struct body: some View {
someView()
.confirmationDialog("", isPresented: $isShowDeleteAlert) {
            Button("delete", role: .destructive) {
                item!.delete(context: context)
                self.detailViewIsShow = false
                presentationMode.wrappedValue.dismiss()
            }
        }
}

CodePudding user response:

you can add onChange() listener in view 2 on "detailViewIsShow" property and when it is false, dismiss current view

.onChange(of: detailViewIsShow) { newValue in
    if !newValue{
        presentationMode.wrappedValue.dismiss()
    }
}
  • Related