Last active
December 17, 2024 15:56
-
-
Save timothycosta/78e87544a90ce1670548407aac556ab3 to your computer and use it in GitHub Desktop.
Create a SwiftUI Animation with the correct curve and duration from UIKit keyboard notifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func animation(from notification: Notification) -> Animation? { | |
guard | |
let info = notification.userInfo, | |
let duration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double, | |
let curveValue = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int, | |
let uiKitCurve = UIView.AnimationCurve(rawValue: curveValue) | |
else { | |
return nil | |
} | |
let timing = UICubicTimingParameters(animationCurve: uiKitCurve) | |
return Animation.timingCurve( | |
Double(timing.controlPoint1.x), | |
Double(timing.controlPoint1.y), | |
Double(timing.controlPoint2.x), | |
Double(timing.controlPoint2.y), | |
duration: duration | |
) | |
} |
This was such a great lead, but on iOS 16 and 15, (or at least 16.4 and 15.5 that I’m testing on) the control points are just linear (0 to 1), you can to take the spring timing parameters instead.
let timing = UICubicTimingParameters(animationCurve: uiKitCurve)
if let springParams = timing.springTimingParameters,
let mass = springParams.mass, let stiffness = springParams.stiffness, let damping = springParams.damping {
return Animation.interpolatingSpring(mass: mass, stiffness: stiffness, damping: damping)
} else {
return Animation.easeOut(duration: duration) // this is the closest fallback
}
with this helper
private extension UISpringTimingParameters {
var mass: Double? {
value(forKey: "mass") as? Double
}
var stiffness: Double? {
value(forKey: "stiffness") as? Double
}
var damping: Double? {
value(forKey: "damping") as? Double
}
}
Still hard to make SwiftUI be exactly in sync, but this is closest I could get.
thx a lot, i'll try. 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
seem like UIKit keyboard animation ?