SwiftUI:onDismiss不会被调用

时间:2019-09-25 20:46:30

标签: ios swift swiftui xcode11 swift5

我的问题是,如果我以编程方式关闭视图,则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")
}

1 个答案:

答案 0 :(得分:0)

@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()
    }
}