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

SwiftUI 如何在应用进入后台时添加带应用logo的模糊视图?

实现方案

你只需要把根布局调整为ZStack,在原有主内容层之上叠加一个仅在非活跃/后台状态显示的logo层即可,修改后的代码如下:

struct ContentView: View {
    
    @Environment(\.scenePhase) var scenePhase
    @State var blurRadius : CGFloat = 0
    @State var showLogo = false

    var body: some View {
        ZStack {
            // 原有主业务视图
            VStack{
                MainView()
            }
            .blur(radius: blurRadius)
            
            // 后台遮罩层
            if showLogo {
                ZStack(alignment: .center) {
                    // 可选:添加半透明蒙层强化信息隐藏效果,不需要可删除
                    Color(UIColor.systemBackground)
                        .opacity(0.2)
                        .ignoresSafeArea()
                    
                    // 替换为你项目内的logo资源名
                    Image("app_logo")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 120, height: 120)
                }
                .transition(.opacity)
            }
        }
        .onChange(of: scenePhase, perform: { value in
            switch value {
            case .active : 
                withAnimation(.easeInOut(duration: 0.2)) {
                    blurRadius = 0
                    showLogo = false
                }
            case .inactive: 
                withAnimation(.easeInOut(duration: 0.2)) {
                    blurRadius = 15
                    showLogo = true
                }
            case .background:
                blurRadius = 20
                showLogo = true
            @unknown default: print("Unknown")
            }
        })
    }
}

说明

  • 不需要额外引入其他依赖,只需要提前把你需要展示的logo导入到项目的Assets资源库中,替换代码里的资源名即可
  • 如果不想额外新增showLogo状态变量,也可以直接用if blurRadius > 0来判断是否显示logo层,逻辑效果完全一致
  • 你可以根据自己的设计需求调整logo的尺寸、蒙层的颜色和透明度,也可以在logo层添加其他你需要展示的提示内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:45:03