Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to blur View with Animation in SwiftUI?

I am blurring a View depending on the Scene Phase. I also added withAnimation { ... }, however, the Blur-Transition happens without any Animation. Check out my Code:

@main struct ExampleApp: App {
    @Environment(\.scenePhase) var scenePhase
    @State private var blurRadius: CGFloat = 0

    var body: some Scene {
        WindowGroup {
            RootView()
                .blur(radius: blurRadius)
                .onChange(of: scenePhase, perform: { value in
                    switch value {
                        case .active : withAnimation { blurRadius = 0 }
                        case .inactive: withAnimation { blurRadius = 15 }
                        @unknown default: print("Unknown")                    
                    }
                })
        }
    }
}

Does anyone have an Idea why the Blur-Status changes without any Animation?

Thank you for your help.

like image 243
christophriepe Avatar asked Sep 15 '25 14:09

christophriepe


1 Answers

Although this behavior doesn't seem to work correctly as the root node inside an App, it does seem to work if you move the blur and animation inside the View:

struct RootView: View {
    @Environment(\.scenePhase) var scenePhase
    @State var blurRadius : CGFloat = 0
    
    var body: some View {
        Text("Hello, world!")
            .blur(radius: blurRadius)
            .onChange(of: scenePhase, perform: { value in
                switch value {
                case .active : withAnimation { blurRadius = 0 }
                case .inactive: withAnimation { blurRadius = 15 }
                @unknown default: print("Unknown")
                }
            })
    }
}
like image 127
jnpdx Avatar answered Sep 17 '25 06:09

jnpdx