[英]SwiftUI: Text issue during animations
I have a problem with an animation that involves a Text
.我对涉及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.可能最烦人的是...
我只想为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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.