我的问题是,如果我以编程方式关闭视图,则不会调用onDismiss中的.sheet。如果我通常通过向下滑动onDismiss消除视图,则通常会调用该方法。

视图1:

HStack {
    Text("Twittere deine Antwort")
    Spacer()
}
.onTapGesture {
    self.showPostCommentView = true
}
.sheet(isPresented: self.$showPostCommentView, onDismiss: {
    self.optionManager.getTweet() // <--- This does not get called
}) {
    PostTweetView(postCommentTweet: self.optionManager.tweet, postTweetImage: self.image, profileImage: self.imageLoader.image)
}


查看2:

@Environment(\.presentationMode) private var presentationMode

Button(action: {
     // some async operations... When finished completion gets called
     self.tweetManager.sendTweet(completion: { self.presentationMode.wrappedValue.dismiss() })
}) {
    Text("Twittern")
}

最佳答案

@escaping闭包添加到PostTweetView并将onDismiss代码添加到闭包。确保您在PostTweetView中的init也分配了所有其本地变量:

PostTweetView

@Environment(\.presentationMode) private var presentationMode
var onDismiss: () -> Void
init(/* All the other local variables in this view */ onDismiss: @escaping () -> Void) {
    // initialize all the other local variables
    self.onDismiss = onDismiss
}

Button(action: {
    // some async operations... When finished completion gets called
    self.tweetManager.sendTweet(completion: {
        self.presentationMode.wrappedValue.dismiss()
        self.onDismiss()
    })
}) {
    Text("Twittern")
}


view1来自您的原始问题:

HStack {
    Text("Twittere deine Antwort")
    Spacer()
}
.onTapGesture {
    self.showPostCommentView = true
}
.sheet(isPresented: self.$showPostCommentView, onDismiss: {
    self.optionManager.getTweet() // <--- This does not get called
}) {
    PostTweetView(postCommentTweet: self.optionManager.tweet, postTweetImage: self.image, profileImage: self.imageLoader.image) {
        self.optionManager.getTweet()
    }
}

08-05 10:04