繁体   English   中英

SwiftUI:动画期间的文本问题

[英]SwiftUI: Text issue during animations

我对涉及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()
    }
}

结果是:

在此处输入图片说明

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

在按钮上试试这个动作:

 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")
 })

并从您的标签中删除该行

 .animation(.easeOut(duration: 1), value: isOn)

我还没有测试它。

可能的替代方法是添加缩放因子,它取代截断模式并提供不同的效果,在某些情况下可能更可取。

唯一需要的变化如下(当然可以修改因素)

Text("\(percentage)")
    .minimumScaleFactor(0.5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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