SwiftUI中事件触发的动画

SwiftUI中事件触发的动画

本文介绍了SwiftUI中事件触发的动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

SwiftUI动画通常由状态驱动,这很棒,但是有时候您真的想触发一个临时(通常是可逆的)动画来响应某些事件。例如,我想在点击按钮时临时增加按钮的大小(释放按钮时,大小的增加和减少都应作为单个动画发生),但是我无法弄清楚



我认为它可以与过渡一起被黑,但不是很好。另外,如果我制作使用自动反转的动画,它将增大大小,减小其大小,然后跳回增大的状态。

解决方案

您可以使用与longPressAction()关联的 @State 变量:





针对Beta 5的代码已更新:



struct ContentView:View {
var body:some View {
HStack {
Spacer()
MyButton(标签: Button 1)
Spacer()
MyButton(标签: Button 2)
Spacer()
MyButton(标签: Button 3)
Spacer()
}
}
}

struct MyButton:View {
let label:String
@State private var press ed = false


变量主体:某些视图{

return Text(label)
.font(.title)
.foregroundColor (.white)
.padding(10)
.background(RoundedRectangle(cornerRadius:10).foregroundColor(.green))
.scaleEffect(self.pressed? 1.2:1.0)
.onLongPressGesture(minimumDuration:.infinity,maximumDistance:.infinity,按下:{按
withAnimation(.easeInOut(duration:0.2)){{
self.pressed =按下
}
},执行:{})
}
}


SwiftUI animations are typically driven by state, which is great, but sometimes you really want to trigger a temporary (often reversible) animation in response to some event. For example, I want to temporarily increase the size of a button when a it is tapped (both the increase and decrease in size should happen as a single animation when the button is released), but I haven't been able to figure this out.

It can sort of be hacked together with transitions I think, but not very nicely. Also, if I make an animation that uses autoreverse, it will increase the size, decrease it and then jump back to the increased state.

解决方案

You can use a @State variable tied to a longPressAction():

Code updated for Beta 5:

struct ContentView: View {
    var body: some View {
        HStack {
            Spacer()
            MyButton(label: "Button 1")
            Spacer()
            MyButton(label: "Button 2")
            Spacer()
            MyButton(label: "Button 3")
            Spacer()
        }
    }
}

struct MyButton: View {
    let label: String
    @State private var pressed = false


    var body: some View {

        return Text(label)
            .font(.title)
            .foregroundColor(.white)
            .padding(10)
            .background(RoundedRectangle(cornerRadius: 10).foregroundColor(.green))
            .scaleEffect(self.pressed ? 1.2 : 1.0)
            .onLongPressGesture(minimumDuration: .infinity, maximumDistance: .infinity, pressing: { pressing in
                withAnimation(.easeInOut(duration: 0.2)) {
                    self.pressed = pressing
                }
            }, perform: { })
    }
}

这篇关于SwiftUI中事件触发的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 07:26