swift 中的链接动画中动画不向上移动

animation not moving upwards in chaining animation in swift

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

  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), width: self.view.frame.width, 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 (可能是一种更简单的说法,但你明白了)

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

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, y: 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 制作“自动反转”风格的动画可能有一种非常简洁和简单的方法,我很想看到其他展示相同概念的示例