3

I'm attempting to dismiss a modal after its intended action is completed, but I have no idea how this can be currently done in SwiftUI. This modal is triggered by a @State value change. Would it be possible to change this value by observing a notification of sorts?

Desired actions: Root -> Initial Modal -> Presents Children -> Dismiss modal from any child

Below is what I've tried

Error: Escaping closure captures mutating 'self' parameter

struct AContentView: View {
    @State var pageSaveInProgress: Bool = false

    init(pages: [Page] = []) { 
    // Observe change to notify of completed action
        NotificationCenter.default.publisher(for: .didCompletePageSave).sink { (pageSaveInProgress) in
            self.pageSaveInProgress = false
        }
    }

    var body: some View {
        VStack {
        //ETC
            .sheet(isPresented: $pageSaveInProgress) {
                    ModalWithChildren()
            }
        }
    }
}

ModalWithChildren test action


Button(action: {
    NotificationCenter.default.post(
        name: .didCompletePageSave, object: nil)}, 
        label: { Text("Close") })
4

1 回答 1

6

您可以接收.onReceive(_:perform)可以在任何视图上调用的消息。它注册一个接收器并将可取消的内容保存在视图中,这使得订阅者与视图本身一样长。

通过它,您可以启动@State属性更改,因为它是从视图主体开始的。否则,您将不得不使用ObservableObject可以从任何地方启动的更改。

一个例子:

struct MyView : View {
    @State private var currentStatusValue = "ok"
    var body: some View {
        Text("Current status: \(currentStatusValue)")
    }
    .onReceive(MyPublisher.currentStatusPublisher) { newStatus in
        self.currentStatusValue = newStatus
    }
}

一个完整的例子

import SwiftUI
import Combine

extension Notification.Name {
    static var didCompletePageSave: Notification.Name {
        return Notification.Name("did complete page save")
    }
}

struct OnReceiveView: View {
    @State var pageSaveInProgress: Bool = true

    var body: some View {
        VStack {
            Text("Usual")
                .onReceive(NotificationCenter.default.publisher(for: .didCompletePageSave)) {_ in
                    self.pageSaveInProgress = false
            }
            .sheet(isPresented: $pageSaveInProgress) {
                ModalWithChildren()
            }
        }
    }
}

struct ModalWithChildren: View {
    @State var presentChildModals: Bool = false

    var body: some View {
        Button(action: {
            NotificationCenter.default.post(
                name: .didCompletePageSave,
                object: nil
            )
        }) { Text("Send message") }
    }
}
于 2019-08-21T06:30:08.990 回答