-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathUIKitAnimation.swift
419 lines (389 loc) · 16.3 KB
/
UIKitAnimation.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#if canImport(UIKit) && !os(watchOS)
import UIKit
import IssueReporting
#if canImport(SwiftUI)
import SwiftUI
#endif
/// Executes a closure with the specified animation and returns the result.
///
/// - Parameters:
/// - animation: An animation, set in the ``UITransaction/uiKit`` property of the thread's
/// current transaction.
/// - body: A closure to execute.
/// - completion: A completion to run when the animation is complete.
/// - Returns: The result of executing the closure with the specified animation.
@MainActor
public func withUIKitAnimation<Result>(
_ animation: UIKitAnimation? = .default,
_ body: () throws -> Result,
completion: (@Sendable (Bool?) -> Void)? = nil
) rethrows -> Result {
var transaction = UITransaction()
transaction.uiKit.animation = animation
if let completion {
transaction.uiKit.addAnimationCompletion(completion)
}
return try withUITransaction(transaction, body)
}
/// The way a view changes over time to create a smooth visual transition from one state to
/// another.
public struct UIKitAnimation: Hashable, Sendable {
fileprivate let framework: Framework
@MainActor
func perform<Result>(
_ body: () throws -> Result,
completion: ((Bool?) -> Void)? = nil
) rethrows -> Result {
switch framework {
case let .swiftUI(animation):
#if swift(>=6)
if #available(iOS 18, macOS 15, tvOS 18, visionOS 2, watchOS 11, *) {
var result: Swift.Result<Result, Error>?
UIView.animate(
with: animation,
changes: { result = Swift.Result(catching: body) },
completion: completion.map { completion in { completion(true) } }
)
return try result!._rethrowGet()
}
#endif
_ = animation
fatalError()
case let .uiKit(animation):
func animations() throws -> Result {
guard let repeatModifier = animation.repeatModifier else { return try body() }
var result: Swift.Result<Result, Error>?
UIView.modifyAnimations(
withRepeatCount: repeatModifier.count,
autoreverses: repeatModifier.autoreverses
) {
result = Swift.Result(catching: body)
}
return try result!._rethrowGet()
}
switch animation.style {
case .iOS4:
var result: Swift.Result<Result, Error>?
withoutActuallyEscaping(animations) { animations in
UIView.animate(
withDuration: animation.duration / animation.speed,
delay: animation.delay / animation.speed,
options: animation.options,
animations: { result = Swift.Result(catching: animations) },
completion: completion
)
}
return try result!._rethrowGet()
case let .iOS7(dampingRatio, velocity):
var result: Swift.Result<Result, Error>?
withoutActuallyEscaping(animations) { animations in
UIView.animate(
withDuration: animation.duration / animation.speed,
delay: animation.delay / animation.speed,
usingSpringWithDamping: dampingRatio,
initialSpringVelocity: velocity,
options: animation.options,
animations: { result = Swift.Result(catching: animations) },
completion: completion
)
}
return try result!._rethrowGet()
case let .iOS17(bounce, initialSpringVelocity):
if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) {
var result: Swift.Result<Result, Error>?
UIView.animate(
springDuration: animation.duration / animation.speed,
bounce: bounce,
initialSpringVelocity: initialSpringVelocity,
delay: animation.delay / animation.speed,
options: animation.options,
animations: { result = Swift.Result(catching: animations) },
completion: completion
)
return try result!._rethrowGet()
} else {
fatalError()
}
}
}
}
fileprivate enum Framework: Hashable, Sendable {
case uiKit(UIKit)
case swiftUI(Animation)
fileprivate struct UIKit: Hashable, Sendable {
fileprivate var delay: TimeInterval
fileprivate var duration: TimeInterval
fileprivate var options: UIView.AnimationOptions
fileprivate var repeatModifier: RepeatModifier?
fileprivate var speed: Double = 1
fileprivate var style: Style
func hash(into hasher: inout Hasher) {
hasher.combine(delay)
hasher.combine(duration)
hasher.combine(options.rawValue)
hasher.combine(repeatModifier)
hasher.combine(speed)
hasher.combine(style)
}
fileprivate struct RepeatModifier: Hashable, Sendable {
var autoreverses = true
var count: CGFloat = 1
}
fileprivate enum Style: Hashable, Sendable {
case iOS4
case iOS7(dampingRatio: CGFloat, velocity: CGFloat)
case iOS17(bounce: CGFloat = 0, initialSpringVelocity: CGFloat = 0)
}
}
}
/// Delays the start of the animation by the specified number of seconds.
///
/// - Parameter delay: The number of seconds to delay the start of the animation.
/// - Returns: An animation with a delayed start.
public func delay(_ delay: TimeInterval) -> Self {
switch framework {
case let .swiftUI(animation):
return UIKitAnimation(framework: .swiftUI(animation.delay(delay)))
case var .uiKit(animation):
animation.delay += delay
return UIKitAnimation(framework: .uiKit(animation))
}
}
/// Repeats the animation for a specific number of times.
///
/// - Parameters:
/// - repeatCount: The number of times that the animation repeats. Each repeated sequence
/// starts at the beginning when `autoreverse` is `false`.
/// - autoreverses: A Boolean value that indicates whether the animation sequence plays in
/// reverse after playing forward. Autoreverse counts towards the `repeatCount`. For
/// instance, a `repeatCount` of one plays the animation forward once, but it doesn't play
/// in reverse even if `autoreverse` is `true`. When `autoreverse` is `true` and
/// `repeatCount` is `2`, the animation moves forward, then reverses, then stops.
/// - Returns: An animation that repeats for specific number of times.
public func repeatCount(_ repeatCount: Int, autoreverses: Bool = true) -> Self {
switch framework {
case let .swiftUI(animation):
return UIKitAnimation(
framework: .swiftUI(animation.repeatCount(repeatCount, autoreverses: autoreverses))
)
case var .uiKit(animation):
animation.repeatModifier = Framework.UIKit.RepeatModifier(
autoreverses: autoreverses,
count: CGFloat(repeatCount)
)
return UIKitAnimation(framework: .uiKit(animation))
}
}
/// Repeats the animation for the lifespan of the view containing the animation.
///
/// - Parameter autoreverses: A Boolean value that indicates whether the animation sequence
/// plays in reverse after playing forward.
/// - Returns: An animation that continuously repeats.
public func repeatForever(autoreverses: Bool = true) -> Self {
switch framework {
case let .swiftUI(animation):
return UIKitAnimation(
framework: .swiftUI(animation.repeatForever(autoreverses: autoreverses))
)
case var .uiKit(animation):
animation.repeatModifier = Framework.UIKit.RepeatModifier(
autoreverses: autoreverses,
count: .infinity
)
return UIKitAnimation(framework: .uiKit(animation))
}
}
/// Changes the duration of an animation by adjusting its speed.
///
/// - Parameter speed: The speed at which SwiftUI performs the animation.
/// - Returns: An animation with the adjusted speed.
public func speed(_ speed: Double) -> Self {
switch framework {
case let .swiftUI(animation):
return UIKitAnimation(
framework: .swiftUI(animation.speed(speed))
)
case var .uiKit(animation):
if speed != 0 {
animation.speed = speed
} else {
reportIssue(
"""
Setting animation speed to zero is not supported for UIKit animations.
Replacing with `.ulpOfOne` to avoid division by zero.
"""
)
animation.speed = .ulpOfOne
}
return UIKitAnimation(framework: .uiKit(animation))
}
}
}
extension UIKitAnimation {
/// Animate changes using the specified duration, delay, and options.
///
/// A value description of `UIView.animate(withDuration:delay:options:animations:completion:)`
/// that can be used with ``withUIKitAnimation(_:_:completion:)``.
///
/// - Parameters:
/// - duration: The total duration of the animations, measured in seconds. If you specify a
/// negative value or `0`, the changes are made without animating them.
/// - delay: The amount of time (measured in seconds) to wait before beginning the animations.
/// Specify a value of `0` to begin the animations immediately.
/// - options: A mask of options indicating how you want to perform the animations. For a list
/// of valid constants, see `UIView.AnimationOptions`.
/// - Returns: An animation with the specified duration, delay, and options.
public static func animate(
withDuration duration: TimeInterval,
delay: CGFloat = 0,
options: UIView.AnimationOptions = []
) -> Self {
Self(
framework: .uiKit(
Framework.UIKit(delay: delay, duration: duration, options: options, style: .iOS4)
)
)
}
/// Performs am animation using a timing curve corresponding to the motion of a physical spring.
///
/// A value description of
/// `UIView.animate(withDuration:delay:dampingRatio:velocity:options:animations:completion:)`
/// that can be used with ``withUIKitAnimation(_:_:completion:)``.
///
/// - Parameters:
/// - duration: The total duration of the animations, measured in seconds. If you specify a
/// negative value or `0`, the changes are made without animating them.
/// - delay: The amount of time (measured in seconds) to wait before beginning the animations.
/// Specify a value of `0` to begin the animations immediately.
/// - dampingRatio: The damping ratio for the spring animation as it approaches its quiescent
/// state.
///
/// To smoothly decelerate the animation without oscillation, use a value of `1`. Employ a
/// damping ratio closer to zero to increase oscillation.
/// - velocity: The initial spring velocity. For smooth start to the animation, match this
/// value to the view's velocity as it was prior to attachment.
///
/// A value of `1` corresponds to the total animation distance traversed in one second. For
/// example, if the total animation distance is 200 points and you want the start of the
/// animation to match a view velocity of 100 pt/s, use a value of `0.5`.
/// - options: A mask of options indicating how you want to perform the animations. For a list
/// of valid constants, see `UIView.AnimationOptions`.
/// - Returns: An animation using a timing curve corresponding to the motion of a physical
/// spring.
public static func animate(
withDuration duration: TimeInterval,
delay: CGFloat = 0,
usingSpringWithDamping dampingRatio: CGFloat,
initialSpringVelocity velocity: CGFloat,
options: UIView.AnimationOptions = []
) -> Self {
Self(
framework: .uiKit(
Framework.UIKit(
delay: delay,
duration: duration,
options: options,
style: .iOS7(
dampingRatio: dampingRatio,
velocity: velocity
)
)
)
)
}
/// Animates changes using a spring animation with the specified duration, bounce, initial
/// velocity, delay, and options.
///
/// A value description of
/// `UIView.animate(springDuration:bounce:initialSpringVelocity:delay:options:animations:completion:)`
/// that can be used with ``withUIKitAnimation(_:_:completion:)``.
@available(iOS 17, macOS 14, tvOS 17, watchOS 10, *)
public static func animate(
springDuration duration: TimeInterval = 0.5,
bounce: CGFloat = 0,
initialSpringVelocity: CGFloat = 0,
delay: TimeInterval = 0,
options: UIView.AnimationOptions = []
) -> Self {
Self(
framework: .uiKit(
Framework.UIKit(
delay: delay,
duration: duration,
options: options,
style: .iOS17(
bounce: bounce,
initialSpringVelocity: initialSpringVelocity
)
)
)
)
}
/// Animates changes using the specified SwiftUI animation.
///
/// - Parameter animation: The animation to use for the changes.
@available(iOS 18, macOS 15, tvOS 18, visionOS 2, watchOS 11, *)
public init(_ animation: Animation) {
self.init(framework: .swiftUI(animation))
}
/// A default animation instance.
public static var `default`: Self {
if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) {
return .animate()
} else {
return .animate(withDuration: 0.35)
}
}
/// An animation that moves at a constant speed.
///
/// - Returns: A linear animation with the default duration.
public static var linear: Self { .linear(duration: 0.35) }
/// An animation that moves at a constant speed during a specified duration.
///
/// - Parameter duration: The length of time, expressed in seconds, that the animation takes to
/// complete.
/// - Returns: A linear animation with a specified duration.
public static func linear(duration: TimeInterval) -> Self {
.animate(withDuration: duration, options: .curveLinear)
}
/// An animation that starts slowly and then increases speed towards the end of the movement.
///
/// - Returns: An ease-in animation with the default duration.
public static var easeIn: Self { .easeIn(duration: 0.35) }
/// An animation with a specified duration that starts slowly and then increases speed towards
/// the end of the movement.
///
/// - Parameter duration: The length of time, expressed in seconds, that the animation takes to
/// complete.
/// - Returns: An ease-in animation with a specified duration.
public static func easeIn(duration: TimeInterval) -> Self {
.animate(withDuration: duration, options: .curveEaseIn)
}
/// An animation that starts quickly and then slows towards the end of the movement.
///
/// - Returns: An ease-out animation with the default duration.
public static var easeOut: Self { .easeOut(duration: 0.35) }
/// An animation with a specified duration that starts quickly and then slows towards the end of
/// the movement.
///
/// - Parameter duration: The length of time, expressed in seconds, that the animation takes to
/// complete.
/// - Returns: An ease-out animation with a specified duration.
public static func easeOut(duration: TimeInterval) -> Self {
.animate(withDuration: duration, options: .curveEaseOut)
}
/// An animation that combines the behaviors of in and out easing animations.
///
/// - Returns: An ease-in ease-out animation with the default duration.
public static var easeInOut: Self { .easeInOut(duration: 0.35) }
/// An animation with a specified duration that combines the behaviors of in and out easing
/// animations.
///
/// - Parameter duration: The length of time, expressed in seconds, that the animation takes to
/// complete.
/// - Returns: An ease-in ease-out animation with a specified duration.
public static func easeInOut(duration: TimeInterval) -> Self {
.animate(withDuration: duration, options: .curveEaseInOut)
}
}
#endif