plu
plu

Reputation: 1351

Simple SwiftUI modal presentation and dismiss via @StateObject

In the given code example the presentation of CreateSomethingView works, however dismissing it does not work. I'm especially interested in making this one work using @StateObject and avoiding @State entirely.

import SwiftUI

@main
struct ModalPresentationApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

final class ContentModel: ObservableObject {
    @Published
    var isPresenting = false
}

struct ContentView: View {
    @StateObject
    var contentModel = ContentModel()

    var body: some View {
        NavigationView {
            Text("ContentView")
                .toolbar {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                            contentModel.isPresenting.toggle()
                        }, label: {
                            Image(systemName: "plus.circle")
                        })
                        .sheet(isPresented: $contentModel.isPresenting) {
                            CreateSomethingView(isPresented: $contentModel.isPresenting)
                        }
                    }
                }
        }
    }
}

struct CreateSomethingView: View {
    @Binding
    var isPresented: Bool

    var body: some View {
        NavigationView {
            Text("CreateSomethingView")
                .toolbar {
                    ToolbarItem(placement: .navigationBarLeading) {
                        Button(action: {
                            isPresented = false
                        }, label: {
                            Image(systemName: "xmark.circle.fill")
                        })
                    }
                }
        }
    }
}

Upvotes: 2

Views: 399

Answers (1)

Asperi
Asperi

Reputation: 258345

Just attach sheet in appropriate location (well... just by experience any *bar(s) is not very good place for inter-views bindings)

Here is fix. Prepared & tested with Xcode 12b5 / iOS 14

var body: some View {
    NavigationView {
        Text("ContentView")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        contentModel.isPresenting = true
                    }, label: {
                        Image(systemName: "plus.circle")
                    })
                }
            }
    }
    .sheet(isPresented: $contentModel.isPresenting) {
        CreateSomethingView(isPresented: $contentModel.isPresenting)
    }
}

Upvotes: 2

Related Questions