淡入淡出动画 Swift

Fade In and Fade out in Animation Swift

我有一个带动画的 UIImageView,在 UIView 中,我应用了淡入效果,但我需要在动画的 UIImageView 被触摸时应用淡出。

这是我淡入淡出的效果。

UIView.animateWithDuration(0.5, delay: delay, 
    options: UIViewAnimationOptions.CurveEaseOut, animations: {
        uiImageView.alpha = 1.0
        }

根据我的研究,我会这样做:(假设您使用的是故事板)

  1. 转到您的 UIImageView,然后在属性下选中 "User Interaction Enabled" 复选框。

  2. 将 TapGestureRecognizer 拖到图像视图的顶部。

  3. 控制点击点击手势并拖动以在您的 ViewControler.swift.

  4. 上执行操作
  5. 在里面添加如下代码:

    UIView.animate(withDuration: 0.5, delay: 0.5, options: .curveEaseOut, animations: {
        self.uiImageView.alpha = 0.0
    }, completion: nil) 
    

大功告成!

从iOS10 开始,Apple 推出了新的iOS Animations SDK,功能更强大,尤其是在计时功能和交互性方面。

使用这种方法淡出代码将:

UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
    self.uiImageView.alpha = 0.0
}).startAnimation()

要了解有关 属性 Animator 的更多详细信息,请查看 iOS 10 Animations demo

Swift 4 .为UIView对象添加淡入淡出功能

extension UIView {

    func fadeIn(_ duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
        UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
            self.alpha = 1.0
    }, completion: completion)  }

    func fadeOut(_ duration: TimeInterval = 0.5, delay: TimeInterval = 1.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in}) {
        UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
            self.alpha = 0.3
    }, completion: completion)
   }
}

例子

label.fadeIn()

label.fadeOut()

imageView.fadeOut(completion: {
    (finished: Bool) -> Void in
    imageView.removeFromSuperview()
})

label.fadeIn(completion: {
    (finished: Bool) -> Void in
    label.text = "Changed!"
})

Swift 5

这对我来说效果很好。我想为标签设置动画,并持续淡入/淡出。我把标签放在 "cardHeaderView".

里面
@IBOutlet weak var cardHeaderView: UIView!

将其放在 "viewDidAppear" 中。我的延迟为零,因此动画会立即开始。

fadeViewInThenOut(view: cardHeaderView, delay: 0)

这是函数。

func fadeViewInThenOut(view : UIView, delay: TimeInterval) {

    let animationDuration = 1.5

    UIView.animate(withDuration: animationDuration, delay: delay, options: [UIView.AnimationOptions.autoreverse, UIView.AnimationOptions.repeat], animations: {
        view.alpha = 0
    }, completion: nil)

}