使用动画移动时获取元素的偏移量

Posted

技术标签:

【中文标题】使用动画移动时获取元素的偏移量【英文标题】: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 值我该怎么做?

【问题讨论】:

你需要你的 AnimatableModifier,然后你可以在 animatableData 中截取改变的值。比如***.com/a/61017784/12299030。 【参考方案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)
            
        
    

【讨论】:

以上是关于使用动画移动时获取元素的偏移量的主要内容,如果未能解决你的问题,请参考以下文章

如何正确获取 DOM 元素的位置偏移量? [复制]

获取元素相对于父容器的位置/偏移量?

获取元素大小偏移量及鼠标位置

获取与窗口相关的元素顶部偏移量

在没有 getBoundingClientRect 的情况下获取相对于文档的元素偏移量(Webkit 错误)

javascript 获取内联元素的偏移量