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
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?
.animation
to the entire sub-hierarchy. This means that if the sub-hierarchy contains other changes that happen in the same transaction as the transition, then all of these changes will inherit the animation which you intended exclusively for the transition. To fix this, you would need the new iOS 17+.animation {}
modifier, but this one would need to be applied at the level where the transition is set, which breaks the animation again (since the animation itself needs to be at the container level). – Ashok