I have a problem with an animation that involves a Text
. Basically I need to change the text and animate its position. Take a look at this simple example here below:
import SwiftUI
struct ContentView: View {
@State private var isOn = false
@State private var percentage = 100
var body: some View {
ZStack {
Text("\(percentage)")
.font(.title)
.background(Color.red)
.position(isOn ? .init(x: 150, y: 300) : .init(x: 150, y: 100))
.animation(.easeOut(duration: 1), value: isOn)
VStack {
Spacer()
Button(action: {
self.isOn.toggle()
//just to make the issue happen
if self.percentage == 100 {
self.percentage = 0
} else {
self.percentage = 100
}
}, label: {
Text("SWITCH")
})
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The result is:
There are some issues here. Probably the most annoying is the glitch with the ...
I just want to animate the position of the Text
, I don't want to animate the text itself and I don't want to animate the width of the text. Any ideas? Thank you.
Try this action on the button:
Button(action:
{
//just to make the issue happen
if self.percentage == 100
{
self.percentage = 0
}
else
{
self.percentage = 100
}
withAnimation(.easeInOut(duration: 1.0)) {
self.isOn.toggle()
}
}, label: {
Text("SWITCH")
})
And remove that line from your Label
.animation(.easeOut(duration: 1), value: isOn)
I didn't test it yet.
The possible alternate is to add scaling factor, it supersedes truncation mode and gives different effect, which under some circumstances might be preferable.
The only needed changes is as below (factor modifiable of course)
Text("\(percentage)")
.minimumScaleFactor(0.5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With