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

iOS16.4+Xcode15.1下SwiftUI多层Sheet文本样式异常求解决方案

iOS 16.4 + Xcode 15.1 SwiftUI Sheet文本异常问题解决方法

在iOS 16.4搭配Xcode 15.1环境中,满足以下条件时,打开第二个Sheet会导致第一个Sheet内的文本字体缩小、部分文本变灰:

  • 从ContentView打开第一个Sheet,再从第一个Sheet打开第二个Sheet
  • ContentView的List包含带自定义header的Section
  • 第一个Sheet内包含Form或List

方案1:调整Sheet的添加位置

原代码将Sheet附加在Section的overlay中,易引发样式继承混乱。改为将Sheet直接添加到NavigationStack或List层级,切断Section样式对Sheet内容的影响:

struct ContentView: View {
    @State private var item: Item?

    var body: some View {
        NavigationStack {
            List {
                Section {
                    Button("Tap to open first sheet") {
                        item = Item()
                    }
                } header: {
                    ListHeaderText(text: "This header causes the bug")
                }
            }
            // 将Sheet移至List层级,避免Section样式传递
            .sheet(item: $item) { item in
                FirstSheetContentView()
                    .textCase(.none) // 显式取消大写样式继承
            }
        }
    }
}

方案2:显式指定Sheet内文本样式

若需保留原有Sheet位置,可在第一个Sheet的内容中显式设置文本、按钮的样式,抵消异常的继承样式:

struct FirstSheetContentView: View {
    @State var showSecondSheet: Bool = false
    
    var body: some View {
        NavigationStack {
            Form {
                Button("Open Second Sheet - this text is smaller after opening the second sheet") {
                    showSecondSheet = true
                }
                .font(.body) // 强制设置字体大小
                .foregroundColor(.primary) // 强制设置文本颜色
                .sheet(isPresented: $showSecondSheet) {
                    SecondSheetContentView()
                }
                Text("This text turns gray after opening the second sheet")
                    .font(.body)
                    .foregroundColor(.primary)
            }
        }
    }
}

方案3:优化Section Header定义

避免自定义Header带来的样式传递问题,可直接使用Text作为Section Header,或为自定义Header添加样式隔离:

// 直接使用Text作为Header
Section {
    Button("Tap to open first sheet") {
        item = Item()
    }
} header: {
    Text("This header causes the bug")
}

// 若需保留自定义Header,添加样式隔离
// Section {
//     Button("Tap to open first sheet") {
//         item = Item()
//     }
// } header: {
//     ListHeaderText(text: "This header causes the bug")
//         .textCase(.none)
//         .environment(\.textCase, nil)
// }

问题原因

该异常源于SwiftUI的环境样式继承冲突:Section的自定义Header会传递特定文本环境变量到Sheet中,当Sheet嵌套且包含Form/List时,关闭第二个Sheet后环境样式未正确重置,从而导致文本显示异常。调整Sheet层级或显式覆盖样式可解决此问题。

内容的提问来源于stack exchange,提问作者John Cashew

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:30:22