gpt4 book ai didi

ios - SwiftUI withAnimation 完成回调

转载 作者:行者123 更新时间:2023-12-01 10:23:18 28 4
gpt4 key购买 nike

我有一个基于某些状态的 swiftUI 动画:

withAnimation(.linear(duration: 0.1)) {
self.someState = newState
}
上述动画完成时是否会触发任何回调?
如果有关于如何在 SwiftUI 中使用完成 block 完成动画的任何建议,而不是 withAnimation ,我也对这些持开放态度。
我想知道动画何时完成,以便我可以做其他事情,就本示例而言,我只想在动画完成时打印到控制台。

最佳答案

这是一个简化和通用的版本,可用于任何单值动画。这是基于我在等待 Apple 提供更方便的方式时在互联网上找到的其他一些示例:

struct AnimatableModifierDouble: AnimatableModifier {

var targetValue: Double

// SwiftUI gradually varies it from old value to the new value
var animatableData: Double {
didSet {
checkIfFinished()
}
}

var completion: () -> ()

// Re-created every time the control argument changes
init(bindedValue: Double, completion: @escaping () -> ()) {
self.completion = completion

// Set animatableData to the new value. But SwiftUI again directly
// and gradually varies the value while the body
// is being called to animate. Following line serves the purpose of
// associating the extenal argument with the animatableData.
self.animatableData = bindedValue
targetValue = bindedValue
}

func checkIfFinished() -> () {
//print("Current value: \(animatableData)")
if (animatableData == targetValue) {
//if animatableData.isEqual(to: targetValue) {
DispatchQueue.main.async {
self.completion()
}
}
}

// Called after each gradual change in animatableData to allow the
// modifier to animate
func body(content: Content) -> some View {
// content is the view on which .modifier is applied
content
// We don't want the system also to
// implicitly animate default system animatons it each time we set it. It will also cancel
// out other implicit animations now present on the content.
.animation(nil)
}
}
这是一个关于如何将它与文本不透明动画一起使用的示例:
import SwiftUI

struct ContentView: View {

// Need to create state property
@State var textOpacity: Double = 0.0

var body: some View {
VStack {
Text("Hello world!")
.font(.largeTitle)

// Pass generic animatable modifier for animating double values
.modifier(AnimatableModifierDouble(bindedValue: textOpacity) {

// Finished, hurray!
print("finished")

// Reset opacity so that you could tap the button and animate again
self.textOpacity = 0.0

}).opacity(textOpacity) // bind text opacity to your state property

Button(action: {
withAnimation(.easeInOut(duration: 1.0)) {
self.textOpacity = 1.0 // Change your state property and trigger animation to start
}
}) {
Text("Animate")
}
}
}
}

struct HomeView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

关于ios - SwiftUI withAnimation 完成回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57763709/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com