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

SwiftUI ProgressView切换布尔值后消失?求原因与解决办法

问题分析与解决办法

这不是SwiftUI的原生Bug,问题出在Section的使用场景不对——Section是为List或Form的分组展示设计的,脱离这个上下文单独使用时,SwiftUI的视图更新机制会出现异常,导致后续切换isLoading为true时无法正确渲染ProgressView。

解决办法有两种:

1. 将Section放入List/Form中(符合Section的设计初衷)

修改后的代码如下:

struct TestProgressView: View {
    @State var isLoading: Bool = false

    var body: some View {
        List {
            Section {
                Button {
                    isLoading.toggle()
                } label: {
                    Text("Toggle Stuff")
                }

                if isLoading {
                    ProgressView()
                } else {
                    Text(isLoading.description)
                }
            }
        }
    }
}

2. 用VStack替换Section(如果不需要列表分组样式)

如果只是需要简单的垂直布局,直接用通用的VStack作为容器即可:

struct TestProgressView: View {
    @State var isLoading: Bool = false

    var body: some View {
        VStack {
            Button {
                isLoading.toggle()
            } label: {
                Text("Toggle Stuff")
            }

            if isLoading {
                ProgressView()
            } else {
                Text(isLoading.description)
            }
        }
        .padding()
    }
}

两种方式都能让视图状态切换时正常渲染对应的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:40:39