【问题标题】:Xcode wait for animation to finish before executing next taskXcode 在执行下一个任务之前等待动画完成
【发布时间】:2019-07-26 12:38:42
【问题描述】:

我有一个图层在我向上滑动时向上移动,然后在我向下滑动时同一图层向下移动。

当我向上滑动时,我不希望用户能够向下滑动以激活该动画,直到向上滑动动画完成,反之亦然。

我该如何做到这一点?我尝试使用“isEnabled”禁用滑动手势,但没有骰子。其他一些类似问题的答案是很久以前的,并且语法非常不同。我正在使用最新版本的 xcode。

【问题讨论】:

  • 能否分享相关代码?
  • func downWaves() { // 移动波浪的函数 let moveDown = CABasicAnimation(keyPath: "position.y") moveDown.fromValue = 550 moveDown.toValue = 843 moveDown.duration = 1 moveDown. timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) moveDown.repeatCount = 1 moveDown.fillMode = CAMediaTimingFillMode.forwards moveDown.isRemovedOnCompletion = false 百层.add(moveDown, forKey: "position")
  • *hundred 是我正在移动的图像
  • 看这个答案stackoverflow.com/a/16337973/7842542。它显示了如何停止动画。也许您可以使用手势识别器来停止动画并开始新的动画
  • 感谢 Malik,我实际上找到了另一种使用presentation() 繁荣的方法。 myImage.layer.presentation()?.position.y -> 这让我可以随时保存图像的 y 位置,这样当我向任何方向滑动时,图像会从最后一个位置开始移动跨度>

标签: swift xcode animation swift4 caanimation


【解决方案1】:

可以通过添加布尔变量、IF 语句以及 DispatchQueue 函数来解决此问题,以防止在当前动画完成之前发生另一个动画。

import UIKit
var animation_active = false
let animation_duration = 2 //For easy maintenance

func swipe_down() {
    if animation_active == false {
        animation_active == true
        //Animation code goes here. Variable 'animation_active' should be used when performing the animation for easy matinence
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(animation_duration), execute: {
            animation_active = false
        })
    }
}
 

func swipe_up() { //This is exactly the same as swipe_up. Yet it will prevent the swipe animation from occuring when the swipe down animation is occuruing thanks to the variable 'animation_active'
    if animation_active == false {
        animation_active == true
        //Animation code goes here. Variable 'animation_active' should be used when performing the animation for easy matinence
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(animation_duration), execute: {
            animation_active = false
        })
    }
}

【讨论】:

  • 这行得通,但唯一的事情是,我希望用户能够无缝地向上或向下滑动,但是当我使用 animation_active 条件时,动画开始前会有一个暂停。我能想到的另一个选择是允许用户随时向上或向下滑动,但这意味着我必须存储图像的最后一个 y 坐标,这样当用户滑动时,动画不会重置所有通往顶部或底部的方式。
猜你喜欢
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
相关资源
最近更新 更多