【问题标题】:Get offset of element while moving using animation使用动画移动时获取元素的偏移量
【发布时间】:2020-11-23 23:10:02
【问题描述】:

如何在移动元素移动的同时获得它的 Y 偏移量?

这是我正在运行的代码:

import SwiftUI

struct testView: View {
    @State var showPopup: Bool = false
    
    var body: some View {
        ZStack {
            VStack {
                Button(action: {
                    self.showPopup.toggle()
                }) {
                    Text("show popup")
                }
                
                
                Color.black
                    .frame(width: 200, height: 200)
                    .offset(y: showPopup ? 0 : UIScreen.main.bounds.height)
                    .animation(.easeInOut)
                
            }
        }
    }
}

struct testView_Previews: PreviewProvider {
    static var previews: some View {
        testView()
    }
}

我想在单击按钮时获取黑色正方形的 Y 值,该正方形将移动到 0 位置但是我想检测正方形何时达到 0 值我该怎么做?

【问题讨论】:

标签: swift xcode swiftui


【解决方案1】:

默认动画持续时间(对于那些没有明确的持续时间参数的动画)通常是 0.25-0.35(独立于它的启动位置和平台),所以在你的情况下它是完全安全的(使用 Xcode 11.4 / iOS 13.4 测试) 使用以下方法:

withAnimation(.spring()){
    self.offset = .zero
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        self.animationRunning = false
    }
}

【讨论】:

    【解决方案2】:

    SwiftUI 不提供动画完成的回调,因此有两种方法可以完成对正方形何时完成动画的检测。

    方法一:使用AnimatableModifier。这是一篇写得很好的Stack Overflow post,关于如何设置它。

    方法 2:在动画完成后使用 Timer 运行。这里的想法是创建一个在计时器完成后运行的计划计时器。

    struct ContentView: View {
        @State var showPopup: Bool = false
        
        var body: some View {
            ZStack {
                VStack {
                    Button(action: {
                        // add addition here with specified duration
                        withAnimation(.easeInOut(duration: 1), {
                            self.showPopup.toggle()
                        })
    
                        // set timer to run after the animation's specified duration
                        _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
                            // run your completion code here eg.
                            withAnimation(.easeInOut(duration: 1)) {
                                self.showPopup.toggle()
                            }
                            timer.invalidate()
                        }
                    }) {
                        Text("show popup")
                    }
                    
                    Color.black
                        .frame(width: 200, height: 200)
                        .offset(y: showPopup ? 0 : UIScreen.main.bounds.height)
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多