SwiftUI - Using Different Transitions on Nested Views
Asked Answered
P

0

12

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
     )
  }
}
Prim answered 6/6, 2021 at 14:32 Comment(6)
Transition works when explicit view (with transition modifier) appears or disappears... any parent or children or sibling is not related to this.Viviyan
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?Prim
@lenny Did you figure out a solution in the end?Glomma
@Glomma 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.Prim
Hi, did yo manage to do it like you said?Blown
Tackled a somewhat similar issue today, this might help with this: #78927641Mei

© 2022 - 2024 — McMap. All rights reserved.