【问题标题】:animation not moving upwards in chaining animation in swift动画在快速链接动画中没有向上移动
【发布时间】:2021-07-08 03:35:03
【问题描述】:

我希望我的 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 - 它正在与其他属性竞争

标签: swift animation position completion chained


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多