首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用UIViewPropertyAnimator通过触摸中断动画

用UIViewPropertyAnimator通过触摸中断动画
EN

Stack Overflow用户
提问于 2018-05-11 07:41:15
回答 1查看 632关注 0票数 0

我正试图通过屏幕触摸来控制动画

当我触摸屏幕时,视图的alpha值为0

但是如果alpha在更改为0时再次接触到

然后alpha再转1次(中断动画使alpha值为0)

所以我写

代码语言:javascript
复制
class MainViewController: UIViewController {

var showAnimation:UIViewPropertyAnimator!
var hideAnimation:UIViewPropertyAnimator!
var isHiding:Bool = false
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .blue

    showAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 1
    })
    hideAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 0
    })
    showAnimation.isUserInteractionEnabled = true
    showAnimation.isInterruptible = true
    hideAnimation.isUserInteractionEnabled = true
    hideAnimation.isInterruptible = true
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    isHiding = !isHiding
    if self.isHiding {
        self.hideAnimation.startAnimation()
        self.showAnimation.stopAnimation(true)
    }else{
        self.hideAnimation.stopAnimation(true)
        self.showAnimation.startAnimation()
    }
}
}

但是只有在动画块完成后才调用touchesBegan。

我如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-11 08:16:49

这里有两件事你需要知道:

  • 在初始化isUserInteractionEnabledisInterruptible之后,不需要将它们设置为true,因为它们的默认值是true。
  • 调用stopAnimation后,UIViewPropertyAnimator将变得无效,您无法调用startAnimation使其再次工作。因此,您需要在停止showAnimationhideAnimation之后重新初始化它们。

要解决问题,请尝试下面的代码。

代码语言:javascript
复制
class MainViewController: UIViewController {

  var showAnimation:UIViewPropertyAnimator!
  var hideAnimation:UIViewPropertyAnimator!
  var isHiding:Bool = false
  override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .blue
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    isHiding = !isHiding
    if self.isHiding {
      self.showAnimation?.stopAnimation(true)

      self.hideAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 0.1
      })
      self.hideAnimation.startAnimation()
    }else{
      self.hideAnimation?.stopAnimation(true)

      self.showAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 1
      })
      self.showAnimation.startAnimation()
    }
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50287405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档