介绍
- 在 iOS 17 之前,UIView Animation 已经提供了弹簧动画的 API。
open class func animate(withDuration duration: TimeInterval,
delay: TimeInterval,
usingSpringWithDamping dampingRatio: CGFloat,
initialSpringVelocity velocity: CGFloat,
options: UIView.AnimationOptions = [],
animations: @escaping () -> Void,
completion: ((Bool) -> Void)? = nil)
- iOS 17 为弹簧动画增加新的 API。
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
@MainActor public class func animate(springDuration duration: TimeInterval = 0.5,
bounce: CGFloat = 0.0,
initialSpringVelocity: CGFloat = 0.0,
delay: TimeInterval = 0.0,
options: UIView.AnimationOptions = [],
animations: () -> Void,
completion: ((Bool) -> Void)? = nil)
参数含义
-
springDuration
:动画持续的时间。 -
bounce
:弹性系数,取值范围 0 ~ 1,数值越大弹性效果越明显。 -
initialSpringVelocity
:初始速度,数值越大初始速度越快。 -
delay
:动画延迟执行的时间。 -
options
:动画的执行效果,可以组合使用。 -
animations
:能够产生动画的具体操作。 -
completion
:动画执行完毕后的操作。
案例
import UIKit
class ViewController: UIViewController {
lazy var redView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 50, width: 100, height: 100))
view.backgroundColor = .red
return view
}()
lazy var greenView: UIView = {
let view = UIView(frame: CGRect(x: 120, y: 50, width: 100, height: 100))
view.backgroundColor = .green
return view
}()
lazy var blueView: UIView = {
let view = UIView(frame: CGRect(x: 240, y: 50, width: 100, height: 100))
view.backgroundColor = .blue
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(blueView)
view.addSubview(greenView)
view.addSubview(redView)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
animate()
}
}
extension ViewController {
// MARK: UIView动画
func animate() {
// 3个不同参数的弹簧动画对比
UIView.animate(springDuration: 1.5, bounce: 0) {
self.redView.center.y = 300
}
UIView.animate(springDuration: 1.5, bounce: 0.5, initialSpringVelocity: 5) {
self.greenView.center.y = 300
}
UIView.animate(springDuration: 1.5,
bounce: 0.9,
initialSpringVelocity: 10,
delay: 0,
options: .curveLinear,
animations: {
self.blueView.center.y = 300
}, completion: nil)
}
}
网友评论