Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI Transition not happening

I am new to SwiftUI and I am trying to use the .transition, but for some reason no transition happens.

You can see the code below:

View

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import SwiftUI

struct ContentView: View {
  @ObservedObject var viewModel = ViewModel()
  
  var body: some View {
    if self.viewModel.model.show {
      Text("Showing")
        .padding()
    } else {
      Text("Not Showing")
        .padding()
        .transition(.asymmetric(insertion: .scale, removal: .opacity))
    }
    
    Button {
      self.viewModel.show()
    } label: {
      Text("Tap to change")
    }
  }
}

ViewModel

class ViewModel: ObservableObject {
  @Published private(set) var model = Model()
  
  func show() {
    self.model.toggleShow()
  }
}

Model

struct Model {
  var show: Bool = true
  
  mutating func toggleShow() {
    self.show.toggle()
  }
}

When I tap the button the text changes but no transition occurs.

I feel like I am missing something trivial here.

Can anyone please assist?

>Solution :

You need an animation (to animate transition) and a container (which performs actual transition, because default implicit Group does not do that).

Here is fixed part of code (tested with Xcode 13.2 / iOS 15.2)

*Note:Preview > Debug > Slow Animation for better visibility

demo

var body: some View {
    VStack {                            // << this !!
        if self.viewModel.model.show {
            Text("Showing")
                .padding()
        } else {
            Text("Not Showing")
                .padding()
                .transition(.asymmetric(insertion: .scale, removal: .opacity))
        }
    }
    .animation(.default, value: self.viewModel.model.show)  // << here !!

    Button {
        self.viewModel.show()
    } label: {
        Text("Tap to change")
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading