You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何实现两个Sheet分别使用不同的Presentation Detents?

解决SwiftUI嵌套Sheet高度被覆盖的问题

问题根源是SwiftUI默认的Sheet交互逻辑:弹出子Sheet时,父级Sheet会自动调整到最小可用高度,导致父Sheet的0.7比例被子Sheet的0.3覆盖。只需给父Sheet添加特定修饰符,就能让父子Sheet各自保持设定高度。

修正后的代码示例:

// 父视图弹出Sheet的代码
Parent.sheet(isPresented: $showParentSheet) {
    ParentContent()
        .presentationDetents([.fraction(0.7)])
        // 关键修饰符:让父Sheet保持自身高度,不被子Sheet压缩
        .presentationBackgroundInteraction(.enabled)
}

// ParentContent内部的子Sheet代码
struct ParentContent: View {
    @State private var showChildSheet = false
    
    var body: some View {
        Button("弹出子Sheet") {
            showChildSheet = true
        }
        .sheet(isPresented: $showChildSheet) {
            ChildContent()
                .presentationDetents([.fraction(0.3)])
        }
    }
}

struct ChildContent: View {
    var body: some View {
        Text("子Sheet内容")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.blue.opacity(0.2))
    }
}

核心说明:

  • presentationBackgroundInteraction(.enabled)会禁用父Sheet在子Sheet弹出时的自动高度压缩逻辑,强制保持其设定的0.7比例。
  • 每个Sheet的presentationDetents独立设置,各自的尺寸不会再互相干扰。

内容的提问来源于stack exchange,提问作者Aaban Tariq Murtaza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:33:11