Swift Infinite淡入和淡出循环
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift Infinite淡入和淡出循环相关的知识,希望对你有一定的参考价值。
对于ios
UIViewAnimationOptions集提供了不同的方便选项,以实现美观和复杂动画的组合。对于您的特定情况,您将需要两个选项。
UIViewAnimationOptions.Repeat
UIViewAnimationOptions.AutoReverse
查看下面的代码以实现。
码:
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.blueColor()
self.view.addSubview(view)
UIView.animateWithDuration(1,
delay: 0,
options: [UIViewAnimationOptions.Autoreverse, UIViewAnimationOptions.Repeat],
animations: {
view.backgroundColor = UIColor.clearColor()
},
completion: nil)
}
}
说明:我创建了一个具有特定框架的视图用于演示目的。
您感兴趣的部分是UIView.animateWithDuration
方法。请注意,我在[UIViewAnimationOptions.AutoReverse, UIViewAnimationOptions.Repeat]
参数中提供了一个数组options
。
这两个选项足以实现如下所述的平滑且永久循环的动画。 https://s3.amazonaws.com/uploads.hipchat.com/37040/1764070/6Iow7n7WiWf6Naz/autoReverse.gif
如果您不想反转动画,只需从UIViewAnimationOptions.AutoReverse
参数中的数组中删除options
即可。你会得到这样的动画。 https://s3.amazonaws.com/uploads.hipchat.com/37040/1764070/8fyRUlzqNHSQI47/noreverse.gif
对于iOS
让viewSquare
成为你问题中蓝色方块的名称。
UIView.animate(withDuration: 0.5, delay: 0, options: [.repeat,.autoreverse], animations: {
viewSquare.alpha = 0.0
}, completion: nil)
我假设您正在为iOS编程。
和duration
一起玩,看看最适合你的是什么:
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
let duration = 0.5
override func viewDidLoad() {
super.viewDidLoad()
self.fadeOut(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func fadeIn(finished: Bool) {
UIView.animateWithDuration(self.duration, delay: 0, options: [.CurveEaseInOut], animations: { self.myView.alpha = 1 } , completion: self.fadeOut)
}
func fadeOut(finished: Bool) {
UIView.animateWithDuration(self.duration, delay: 0, options: [.CurveEaseInOut], animations: { self.myView.alpha = 0 } , completion: self.fadeIn)
}
}
如果你想要可重复的淡入淡出动画你可以通过使用如下的CABasicAnimation
来做到这一点:
First create handy UIView extension :
extension UIView {
enum AnimationKeyPath: String {
case opacity = "opacity"
}
func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
let flash = CABasicAnimation(keyPath:.opacity.rawValue)
flash.duration = duration
flash.fromValue = 1 // alpha
flash.toValue = 0 // alpha
flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
flash.autoreverses = true
flash.repeatCount = repeatCount
layer.add(flash, forKey: nil)
}
}
How to use it:
// You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
以上是关于Swift Infinite淡入和淡出循环的主要内容,如果未能解决你的问题,请参考以下文章
Swift3 淡入/淡出或平滑过渡 UIImageView animationImages