Leon Vladimirov
Leon Vladimirov

Reputation: 141

Why does the edgesIgnoringSafeArea modifier get applied after a transition ends in SwiftUI?

I want to overlay the UIScreen with an opacity transition. This is my view:

struct ContentView: View {
    @State private var overlayUIScreen: Bool = false

    var body: some View {
        ZStack {
            if overlayUIScreen {
                Rectangle()
                    .edgesIgnoringSafeArea(.top)
                    .frame(width: UIScreen.main.bounds.size.width,
                           height: UIScreen.main.bounds.size.height)
                    .foregroundColor(Color.gray)

                    .transition(.opacity)
            }

            Button("Overlay?") {
                withAnimation {
                    self.overlayUIScreen.toggle()
                }
            }

        }
    }
}

For some reason the Safe Area changes color after the transition is already finished.
Why does this happen and what can I do to fix this behavior?

Upvotes: 2

Views: 1079

Answers (2)

sfung3
sfung3

Reputation: 2377

Another solution would be to move the frame to modify the ZStack instead of the Rectangle

struct ContentView: View {
    @State private var overlayUIScreen: Bool = false

    var body: some View {
        ZStack {
            if overlayUIScreen {
                Rectangle()
                    .edgesIgnoringSafeArea(.top)
                    .foregroundColor(Color.gray)
                    .transition(.opacity)
            }

            Button("Overlay?") {
                withAnimation {
                    self.overlayUIScreen.toggle()
                }
            }
        }
        .frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
    }
}

Upvotes: 2

Leon Vladimirov
Leon Vladimirov

Reputation: 141

A workaround would be to already have your view in the hierarchy and attribute it's opacity to a @State private var like so:

struct ContentView: View {
    @State private var overlayOpacity: Double = 0.0

    var body: some View {
        ZStack {

            Rectangle()
                 .edgesIgnoringSafeArea(.top)
                 .frame(width: UIScreen.main.bounds.size.width,
                        height: UIScreen.main.bounds.size.height)

                 .opacity(overlayOpacity)

                 .foregroundColor(Color.gray)

            Button("Overlay?") {
                withAnimation {
                    if self.overlayOpacity == 0.0 {
                        self.overlayOpacity = 1.0
                    } else {
                        self.overlayOpacity = 0.0
                    }
                }
            }

        }  .transition(.opacity)
    }
}

Upvotes: 0

Related Questions