10

How can I have an overlaying view in SwiftUI with a different transition on different portions? E.g. in my concrete example, I want to achieve the following:

  • one subview of the overlay view slides in from the bottom
  • another subview of the overlay view has no transition at all (appears instantly)
  • the background of the overlay does not slide in from the bottom but fades in

I've already tried all sorts of things and it seems, that I have to set animation and transition on the view that wraps the if showOverlay condition. However, it looks like all the .transition() and .animation() modifiers set on the sub-views of the overlay are ignored then.

Is it actually possible? The following code is what I thought should somewhat work but apparently doesn't at all:

// any observable external variable, that enables / disables the overlay
@State showOverlay: bool = false

// surrounding view
VStack { /* .. */ }
  .frame(maxWidth: .infinity, maxHeight: .infinity)
  .overlay(
    Group {
      if showOverlay {
        Overlay()
      }
    }
  )

// overlay view
struct Overlay: View {
  var body: some View {
     VStack {
        // style 1
        Text("OverlayContent that slides in from bottom")
           .transition(.move(edge: .bottom).combined(with: .opacity))
           .animation(.easeInOut(duration: 0.28))
        // style 2
        Text("OverlayContent that appears instant")
           .animation(nil)
     }
     .background( // style 3
       Color.black.opacity(0.2)
         .ignoresSafeArea()
         .transition(.opacity) // <-- background should not slide up but fade in
     )
  }
}
Leo
  • 1,508
  • 13
  • 27
  • 2
    Transition works when explicit view (with transition modifier) appears or disappears... any parent or children or sibling is not related to this. – Asperi Jun 06 '21 at 15:56
  • 2
    So that kind of animation I'm looking for is simply not possible except I somehow make each element that has a `.transition` inside it's own conditional block? – Leo Jun 06 '21 at 16:36
  • 1
    @lenny Did you figure out a solution in the end? – lazarevzubov Apr 26 '22 at 14:04
  • @lazarevzubov I think the only way you could do it is to put each transition in it's distinct conditional block controlled by an individual State variable. – Leo Apr 26 '22 at 16:16
  • Hi, did yo manage to do it like you said? – WedgeSparda Aug 26 '22 at 11:51

0 Answers0