简体   繁体   中英

SwiftUI: Text issue during animations

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM