SwiftUI中NavigationLink后用presentationDetents的selection放大Sheet致视图截断
iOS 16+ Sheet 切换尺寸时视图截断问题与临时修复方案
问题现象
自iOS 16起,.sheet修饰器新增presentationDetents特性,支持通过selection绑定参数以编程方式调整Sheet尺寸。但存在以下异常:
- 当通过
NavigationLink跳转页面后,立即将Sheet从PresentationDetent.medium切换至PresentationDetent.large,Sheet内的视图会出现截断 - 轻微拖动调整Sheet后,截断现象会消失,但视图层级仍存在异常
临时解决办法
为Sheet尺寸调整操作添加0.6秒延迟,即可规避截断问题。核心代码片段:
.onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { currentSelection = .large } }
完整示例代码
import SwiftUI struct ContentView: View { @State private var sheetIsOpened = false @State private var currentSelection = PresentationDetent.medium var body: some View { Text("Click to open a sheet") .padding() .onTapGesture { sheetIsOpened = true } .sheet(isPresented: $sheetIsOpened) { NavigationStack { List { ScrollView { ForEach(0..<100) { index in VStack { NavigationLink(destination: NavigatedView(currentSelection: $currentSelection)) { Text("I have the index: \(index)") .foregroundColor(.green) } } .frame(maxWidth: .infinity) } } .padding() } } .presentationDetents([.medium, .large], selection: $currentSelection) } } } struct NavigatedView: View { @Binding fileprivate var currentSelection: PresentationDetent var body: some View { ScrollView { ForEach(0..<100) { index in VStack { Text("I'm a child and I have the index: \(index)") .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { currentSelection = .large } } } .frame(maxWidth: .infinity) } } .background(.red) .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
内容的提问来源于stack exchange,提问作者Gipfeli
相关产品推荐
相关产品推荐

