首页 > 解决方案 > 无法使用 UIViewPropertyAnimator.fractionComplete 驱动 UIView.transition

问题描述

我正在尝试使用滑块驱动具有 2 个图像值(在此示例中)的 UIImageView 的转换,但在 aUIView.transition内使用UIViewPropertyAnimator(应该可以工作)它没有。我错过了什么吗?

let animator = UIViewPropertyAnimator(duration: 3.0, curve: .linear)

let crossDissolve = {
  self.imageView.image = UIImage(named: "deadpool.jpg")
  UIView.transition(
    with: self.imageView,
    duration: 4.0,
    options: .transitionCrossDissolve,
    animations: {},
    completion: nil
  )
}

animator.addAnimations(crossDissolve)

这是一个带有问题示例的游乐场,只需将滑块从一侧拖动到另一侧,图像应该会柔和地交叉溶解

就像是:

图像

游乐场:https ://www.dropbox.com/s/ix8nfxg43ij68q3/UIViewPropertyAnimator.playground.zip?dl=0

标签: iosswiftuiviewpropertyanimator

解决方案


在提供的代码中,您没有在动画闭包中定义任何动画,我对这个 API 并不太熟悉,但我认为您会想要这样的东西。(我没有测试过这段代码)

let animator = UIViewPropertyAnimator(duration: 3.0, curve: .linear)

let crossDissolve = {
  UIView.transition(
    with: self.imageView,
    duration: 4.0,
    options: .transitionCrossDissolve,
    animations: {
        self.imageView.image = UIImage(named: "deadpool.jpg")
    },
    completion: nil
  )
}

animator.addAnimations(crossDissolve)

然后,您可以使用在滑块.valueChanged事件上调用的函数来处理动画进度

slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged) 

func sliderValueChanged(sender: UISlider) {
    myAnimation.fractionComplete = CGFloat(sender.value)
}

推荐阅读