Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Text issue during animations

Tags:

ios

swift

swiftui

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:

enter image description here

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.

like image 459
matteopuc Avatar asked Feb 22 '20 17:02

matteopuc


2 Answers

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.

like image 71
davidev Avatar answered Oct 26 '22 07:10

davidev


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)
like image 39
Asperi Avatar answered Oct 26 '22 06:10

Asperi