Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

ios - SwiftUI EditButton() does not work when set editMode in NavigationLink

I have EditNoteHost view which displays NoteView or EditNote depending on editMode environment variable. Aslo Cancel button is displayed in edit mode:


struct EditNoteHost: View {
    @EnvironmentObject var modelData: ModelData
    @Environment(.editMode) var editMode
    
    @State private var draftNote = Note.default
    
    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            
            HStack {
                if editMode?.wrappedValue == .active {
                    Button("Cancel") {
                        draftNote = modelData.selectedNote
                        editMode?.animation().wrappedValue = .inactive
                    }
                }
                Spacer()
                EditButton()
            }
            
            if editMode?.wrappedValue == .inactive {
                NoteView(note: modelData.selectedNote)
            } else {
                EditNote(note: $draftNote)
                    .onAppear {
                        draftNote = modelData.selectedNote
                    }
                    .onDisappear {
                        modelData.selectedNote = draftNote
                    }
            }
        }
        .padding()
    }
}

struct EditNoteHost_Previews: PreviewProvider {
    static var previews: some View {
        EditNoteHost()
            .environmentObject(ModelData())
    }
}

This code works fine.

Now I want to use EditNoteHost in NavigationLink and start it in edit mode:

NavigationLink(destination: EditNoteHost().environment(.editMode, Binding.constant(EditMode.active)).environmentObject(modelData)) {
                    Image(systemName: "plus")
                }

This part of code opens EditNoteHost in edit mode if click +. However, Done and Cancel buttons do nothing when tap.

How can I fix this?

Screenshot

question from:https://stackoverflow.com/questions/65936588/swiftui-editbutton-does-not-work-when-set-editmode-in-navigationlink

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are setting editMode using .constant(EditMode.active), it will remain active. So do not set the environment for editMode; instead use:

NavigationLink(destination: EditNoteHost()) {
    Image(systemName: "plus")
}

and in EditNoteHost, use

.onAppear() {
    editMode?.animation().wrappedValue = .active
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...