For example, this is what happening right now
struct ContentView: View {
@State var titleLable = "This is basic text"
@State var isTextAnimated: Bool = false
var body: some View {
VStack {
Text(titleLable)
.offset(y: isTextAnimated ? 300 : 0)
.animation(.linear)
Button {
isTextAnimated.toggle()
if isTextAnimated {
titleLable = "New text appeared"
} else {
titleLable = "This is basic text"
}
} label: {
Text("Press")
}
}
.padding()
}
The code above leads to this in Live Preview:
click there
This happens if text doesn’t change its value ( I need this behaviour with changing ):
click there
4
Answers
edit: I forgot to animate the text change
A good way to animate such change is to animate the offset value rather than toggle a boolean:
or by using a boolean value:
Note the important
withAnimation
that indicates to SwiftUI that you want to animate the changes made in the block. You can find the documentation hereThe
.animation(...)
is optional and used if you want to change the behavior of the animation, such as using a spring, changing the speed, adding a delay etc… If you don’t specify one, SwiftUI will use a default value. In a similar fashion, if you don’t want a view to animate, you can use add the.animation(nil)
modifier to prevent SwiftUI from animating said view.Both solutions provided result in the following behavior : https://imgur.com/sOOsFJ0
To animate the position and the content of the
Text
label, you can usematchedGeometryEffect
, as follows:One of the simplest way to achieve this animation is to embed two
Text
inside aZStack
and modify their opacity, and modify the ZStack’s offset rather than the individual Texts. in this way both the offset and the change between two texts will get animated. here is my code:As an alternative to
.matchedGeometryEffect
to animate moving and changing value ofText
view you can "rasterize" text using.drawingGroup()
modifier forText
. This makes text behave like shape, therefore animating smoothly. Additionally it’s not necessary to define separate with linked with.machtedGeometryEffect
modifier which can be impossible in certain situation. For example when new string value and position is not known beforehand.Example
More informations
Apple’s documentation about .drawingGroup modifier