如何在SwiftUI中动画化/转换文本值更改 [英] How to animate/transition text value change in SwiftUI

查看:54
本文介绍了如何在SwiftUI中动画化/转换文本值更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 withAnimation 为文本中的值更改设置动画,但是它似乎不起作用.我遇到了类似的问题,但是

我已经尝试过此代码,但是它不能使文本更改动起来:

  struct TextAnimationView:视图{@State private var textValue ="0&";var body:some View {VStack(间距:50){文字(textValue).font(.largeTitle).frame(宽度:200,高度:200).transition(.opacity)按钮(下一步"){withAnimation(.easeInOut(duration:1)){self.textValue ="\(Int.random(in:1 ... 100))"}}}}} 

我对SwiftUI的经验很少,还有另一种方法可以实现这一目标吗?

先谢谢您了:)

解决方案

事实证明,这确实很简单

  Text(textValue).font(.largeTitle).frame(宽度:200,高度:200).transition(.opacity).id("MyTitleComponent" + textValue) 

请注意最后的其他 id .SwiftUI使用它来决定在重绘时是否正在处理相同的视图.如果id不同,则假定已删除上一个视图,并且已添加了该视图.因为它正在添加新视图,所以将按预期应用指定的过渡.

注意:此ID在整个视图树中很可能是唯一的,因此您可能要注意相应地为其命名空间(因此在示例中为 MyTitleComponent 前缀).

I am trying to animate value change in a text using withAnimation but it doesn't seem to work. I have come across a similar question but the answer is not animating the text value.

I am trying to recreate this behaviour in pure SwiftUI (UIKit Example):

I have tried this code but it doesn't animate the text change:

struct TextAnimationView: View {
    @State private var textValue = "0"
    var body: some View {
        VStack (spacing: 50) {
            Text(textValue)
                .font(.largeTitle)
                .frame(width: 200, height: 200)
                .transition(.opacity)
            Button("Next") {
                withAnimation (.easeInOut(duration: 1)) {
                    self.textValue = "\(Int.random(in: 1...100))"
                }
            }
        }
    }
}

I have a very little experience with SwiftUI, is there another way to achieve this?

Thanks in advance :)

解决方案

So it turns out this is really easy

Text(textValue)
  .font(.largeTitle)
  .frame(width: 200, height: 200)
  .transition(.opacity)
  .id("MyTitleComponent" + textValue)

Note the additional id at the end. SwiftUI uses this to decide if it's dealing with the same view or not when doing a redraw. If the id is different then it assumes the previous view was removed and this one has been added. Because it's adding a new view it applies the specified transition as expected.

NB: It's quite possible that this id should be unique for the entire view tree so you probably want to take care to namespace it accordingly (hence the MyTitleComponent prefix in the example).

这篇关于如何在SwiftUI中动画化/转换文本值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆