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

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

问题描述

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

我已经尝试过这段代码,但它没有为文本更改设置动画:

struct TextAnimationView: View {@State private var textValue = "0";var主体:一些视图{VStack(间距:50){文本(文本值).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天全站免登陆