SwiftUI Tutorial EditMode

In section 2 of "Working with UI Controls" the instructions state to add `@Environment(\.editMode) var mode` to the `ProfileHost` view and use that binding to show either the profile summary or the profile editor:


if self.mode?.value == .inactive { 
    ProfileSummary(profile: profile) 
} else { 
    Text("Profile Editor") 
}


When previewing the canvas in live mode it seems the `mode` variable is always nil and thus it never shows the profile editor. Tapping the edit button seems to have no effect.

Answered by tomwilson in 363472022

I believe it's a bug - if you actually run your app it will work as expected

Accepted Answer

I believe it's a bug - if you actually run your app it will work as expected

FWIW, I'm having the same issue (but things _do_ behave correctly when I run the app).


Xcode 11 GM

MacOS Catalina Beta 8

I'm having the same problem. But yeah it works when you run the app on the simulator. So if any Apple guys seeing this, there's something other weird thing too. The animation of the HikeView() when the "chevron.right.circle" button is pressed is totally off.

This happens because there's nothing adding a binding to an EditMode variable in the environment, so the value you pull from the environment is nil. A real UIHostingController does this, but it appears the canvas scaffolding doesn't, so you have to add it yourself. You can't just use plain @State to generate an @Binding inside ProfileHost_Previews.previews, because it'll crash complaining that you can't do that outside of a body implementation. So, when I was going through this, I built a wrapper to use for the preview:


struct EditModeInPreview<Content: View> : View {
    var content: Content
    @State var editMode: EditMode = .inactive
    
    var body: some View {
        content.environment(\.editMode, $editMode)
    }
    
    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
}

struct ProfileHost_Previews: PreviewProvider {
    static var previews: some View {
        EditModeInPreview {
            ProfileHost()
        }
        .environmentObject(UserData())
    }
}


Share and Enjoy!

To follow up on hakim.id.id's comment, this is still the case. The tutorial has quite a few little quirks and bugs like this.
I understand the technology is new, but how are the rest of us meant to learn it, if Apple cannot put together a functional tutorial?
@Jim+Dovey, thank you, that code worked like a charm... and a clear example of what EditMode and the binding does!

@Hanse00, it's true that a big company like Apple gets things wrong, probably all the time. As for how you can still learn in spite of their shortcomings, I recommend trying the code sample from Jim+Dovey, it'll make you think a bit more than the tutorial does and it will solve the problem that this thread is about.
SwiftUI Tutorial EditMode
 
 
Q