iOS15 SwiftUI关闭sheet后跳转的目标View立即被弹出问题
问题根因
iOS15的SwiftUI存在导航栈状态识别异常的问题:你同时触发sheet关闭和NavigationLink激活两个状态变更时,系统在重绘视图的过程中会误判导航栈的激活状态,导致刚push的C视图被自动pop。你当前代码里在B视图的按钮点击事件中同时修改closeView和showChatView两个绑定状态,正好触发了这个系统bug。
解决方法
调整状态变更时序:先只关闭sheet,等sheet完全关闭后再触发C视图的push操作,避免两个状态变更同时执行冲突。
具体修改如下:
1. View A 代码调整
新增状态标记sheet关闭后是否需要跳转,在sheet的onDismiss回调中执行跳转逻辑:
import SwiftUI struct A: View { @State private var showNewMessage = false @State private var showChatView = false // 新增状态:标记sheet关闭后是否需要跳转C视图 @State private var shouldPushChatAfterDismiss = false var body: some View { ZStack(alignment: .bottomTrailing){ NavigationLink( destination: C(), isActive: $showChatView, label: {}) ScrollView { VStack(alignment: .leading) { ForEach(1...10, id: \.self){_ in NavigationLink( destination: C(), label: { ChatView() }) } } } Button(action: { showNewMessage = true }, label: { Image(systemName: "pencil") .resizable() .scaledToFit() .frame(width: 24, height: 24) }) .padding() .foregroundColor(Color.white) .background(Color.blue) .clipShape(Circle()) .sheet(isPresented: $showNewMessage, onDismiss: { // sheet完全关闭后判断是否需要跳转 if shouldPushChatAfterDismiss { showChatView = true shouldPushChatAfterDismiss = false } }, content: { // 传入新增的状态绑定 B(shouldPushChat: $shouldPushChatAfterDismiss, closeView: $showNewMessage) }).navigationViewStyle(StackNavigationViewStyle()) } .padding(.horizontal) } }
2. View B 代码调整
按钮点击时只标记跳转状态、关闭sheet,不直接触发跳转:
import SwiftUI struct B: View { @Binding var shouldPushChat: Bool @Binding var closeView: Bool var body: some View { Button(action: { shouldPushChat = true closeView = false }, label: { Text("Toggle") }) } }
内容的提问来源于stack exchange,提问作者Jose Ricardo Citerio Alcala
相关产品推荐
相关产品推荐

