0

I was working on a more complicated screen with a lots of data and I noticed weird behavior when edit mode is embedded in navigation view. Following example work as intended - which means text changes between editing and not editing. However when embedded in navigation view, the behavior changes (text remains the same) both in previews and on simulator. Whether the if-else is hooked to editMode itself or to .isEditing does not matter.

Can anyone refer me to resources that would explain why? What am I missing

import SwiftUI

struct ContentView: View {
    
    @Environment(\.editMode) var editMode
    
    var body: some View {
        VStack {
            HStack {
                Spacer()
                EditButton()
            }
            Spacer()
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            if editMode?.wrappedValue == .inactive {
                Text("Not editing")
            } else {
                Text("Editing")
            }
            
            Spacer()
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView { // if removed, the text will change
            ContentView()
        }
    } // NavigationView end
}

1 Answer 1

0

Here is a workaround for my similar case.

struct RootView: View {
    @State private var editMode = EditMode.inactive
    var body: some View {
        NavigationView {
            ContentView()
                .environment(\.editMode, $editMode)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        RootView()
    }
}

The point is .environment() should be applied to the view inside NavigationView.

I suppose the reason for the unexpected behavior is multiple Binding<EditMode> instances for environment's editMode are used among views and the code above may avoid redefining another instance.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.