Post

Replies

Boosts

Views

Activity

Reply to So... AnimatableModifier is now deprecated, but how to "use Animatable directly"?
I can't seem to update my post now. But the two code snippets are pasted below. struct OffsetAnimation: AnimatableModifier{ typealias T = CGFloat var animatableData: T{ get { value } set { value = newValue print("animating \(value)") if watchForCompletion && value == targetValue { DispatchQueue.main.async { [self] in onCompletion() } } } } var watchForCompletion: Bool var value: T var targetValue: T init(value: T, watchForCompletion: Bool, onCompletion: @escaping()->()){ self.targetValue = value self.value = value self.watchForCompletion = watchForCompletion self.onCompletion = onCompletion } var onCompletion: () -> () func body(content: Content) -> some View { return content.offset(x: 0, y: value).animation(nil) } } struct DemoView: View { @State var offsetY: CGFloat = .zero var body: some View { Rectangle().frame(width: 100, height: 100, alignment: .center) .modifier( OffsetAnimation(value: offsetY, watchForCompletion: true, onCompletion: {print("translation complete")})) .onAppear{ withAnimation{ offsetY = 100 } } } } struct RectView: View, Animatable{ typealias T = CGFloat var animatableData: T{ get { value } set { value = newValue print("animating \(value)") } } var value: T var body: some View{ Rectangle().frame(width: 100, height: 100, alignment: .center) .offset(y:value).animation(nil) } } struct DemoView: View{ @State var offsetY: CGFloat = .zero var body: some View { RectView(value: offsetY) .onAppear{ withAnimation{ offsetY = 100 } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Jan ’22