SwiftUI:动画期间的文本问题

sup*_*cio 5 ios swift swiftui

我对涉及Text. 基本上我需要更改文本并为其位置设置动画。看看下面这个简单的例子:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

结果是:

在此处输入图片说明

这里有一些问题。可能最烦人的是小故障,...我只想为 的位置设置动画Text,我不想为文本本身设置动画,也不想为文本的宽度设置动画。有任何想法吗?谢谢你。

dav*_*dev 3

在按钮上尝试此操作:

 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")
 })
Run Code Online (Sandbox Code Playgroud)

并从标签中删除该行

 .animation(.easeOut(duration: 1), value: isOn)
Run Code Online (Sandbox Code Playgroud)

我还没测试过。