动画在快速链接动画中没有向上移动

问题描述

我希望我的 swift 代码遵循我创建的 gif。发生的事情是在第一个动画之后位置没有任何变化。就像我创建的 gif 一样,它应该先向下移动然后再向上移动。我试着乘以负数 -0.15 认为它会朝北。目前没有效果

enter image description here

  UIView.animate(withDuration: 1,animations: {
        self.block1.frame = CGRect(x: 0,y: self.view.frame.height * 0.15,width: self.view.frame.width,height: self.view.frame.height * 0.1)
        self.block1.center = self.view.center
    }) { done in

        /// first animation finished,start second
        if done {
            UIView.animate(withDuration: 1,animations: {
                
                self.block1.frame = CGRect(x: 0,y: self.view.frame.height * (-0.15),height: self.view.frame.height * 0.1)
                
                
                self.block1.center = self.view.center
                
            })
        }
    }

解决方法

首先去掉 self.block1.center = self.view.center,因为您要使块的中心点与两个循环中的视图相同。

self.view.frame.height * (-0.15) 正在视图之外设置一个绝对位置,不确定这是否是故意的,但您可能想知道它。相反,如果您只想移动给定的距离,比如视图的高度,您应该使用相对位置,例如 block1.frame.origin.y -= block.frame.size.height (可能更简单的说法,但你明白了)

所以我创建了一个非常快速的 Playground,创建了一些值并得到了一个“有点”有弹性、返回的东西作为例子

Quick example

import UIKit
import XCPlayground

let view = UIView(frame: CGRect(x: 0.0,y: 0.0,width: 300.0,height: 600.0))
// XCPShowView("container",view: container)  // -> deprecated

let block1 = UIView(frame: CGRect(x: 0.0,width: (view.frame.width) / 2,height: 150))
block1.backgroundColor = UIColor.green
block1.center.x = view.center.x
view.addSubview(block1)

UIView.animate(withDuration: 1,animations: {
    let y = view.frame.height * 0.15
    print(y)
    block1.center.y = view.center.y
}) { done in
    print("Done = \(done)")
    /// first animation finished,start second
    if done {
        UIView.animate(withDuration: 1,animations: {
            block1.frame.origin.y = 0
        })
    }
}

XCPlaygroundPage.currentPage.liveView = view

警告:使用 CALayer 制作“自动反转”风格的动画可能是一种非常简洁且简单的方法,我很想看到其他展示相同概念的示例