【问题标题】:SwiftUI Animation BindingsSwiftUI 动画绑定
【发布时间】:2022-07-21 16:12:11
【问题描述】:
struct ContentView: View {
    @State private var animationAmount = 1.0
    var body: some View {
        VStack
        {
            Stepper("Scale amount", value: $animationAmount.animation(.linear), in: 1...10)
            
            
            
            Spacer()
            Button("Tap Me")
            {
                animationAmount += 1
            }
            .padding(50)
            .background(.red)
            .foregroundColor(.white)
            .clipShape(Circle())
            .scaleEffect(animationAmount)
           
        }
    }
}

所以我有一个小问题,在这里我创建了一个 Stepper 视图,其值是变量的某种方式的两个绑定,然后我在该绑定上调用了 .animation 方法,据我所知,如果该绑定发生任何变化他们只是得到动画。 我的问题是,是否只有与动画绑定值相关的更改?或者如果这个视图发生了其他一些变化,但巧合的是它们发生在绑定发生变化之前,这些变化也会被动画化吗?

还有一个超级超级小问题,为什么我不能在这个 VStack 中添加一个 if 语句来增加 animationAmount? 喜欢

if animationAmount > 1.0
{
   animationAmount += 0.25
}

只是说 () 不符合 View。

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    根据定义,.animation(_:value:) 是:

    当值发生变化时,将动画应用于此视图的视图。

    所以是的,动画仅在您传递的值发生变化时应用,查看更多:.animation(_:value:)

    回答你的第二个问题,VStack, HStack,... & bodyViewBuilders。这意味着它们要求您传入View,而animationAmount += 0.25 的类型为Void != View。所以你应该做的是使用.onChange:

    .onChange(of: animationAmount) { newValue in
        if animationAmount > 1.0 {
            animationAmount += 0.25
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 2021-04-04
      相关资源
      最近更新 更多