【问题标题】:Getting an object to reset to a fixed (x,y) coordinate when a button is pressed in Swift在 Swift 中按下按钮时让对象重置为固定的 (x,y) 坐标
【发布时间】:2017-06-06 00:28:48
【问题描述】:

我有一个填满屏幕的框和一个按钮。当我按下按钮时,我希望框慢慢地向下移动,直到它不再可见。如果在此动画期间按下按钮,我希望按钮返回其原始位置,并恢复动画。我有以下代码:

@IBOutlet weak var backgroundthing: UIView!

@IBAction func button(_ sender: UIButton) {

    UIView.animate(withDuration: 0.0, animations: {self.backgroundthing.frame.origin.y = 0}, completion: nil)

    UIView.animate(withDuration: 4.0, animations: {self.backgroundthing.frame.origin.y = 667}, completion: nil)

}

如果我按下按钮一次,它会“正常”工作,并且该框需要 4 秒才能离开屏幕。但是,如果我在动画结束之前按下按钮,框会捕捉到比其原始位置更高的位置。例如,如果我在框仅离开屏幕一半时按下按钮,它将捕捉到顶部,屏幕上方的一半框继续向下滑动。我正在寻找的代码会将框捕捉到其原始位置,因此无论我按下按钮多快或多少次,它都不会高于其原始位置。

【问题讨论】:

    标签: swift xcode animation uiview


    【解决方案1】:

    先停止动画,重置方块,开始新的动画:

    @IBAction func button(_ sender: UIButton) {
        backgroundthing.layer.removeAllAnimations()
        backgroundthing.frame.origin.y = 0
        UIView.animate(withDuration: 4.0) {
            self.backgroundthing.frame.origin.y = 667
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多