I am wondering how I can animate the content size of a ViewBuilder view. I have this:
struct CardView<Content>: View where Content: View {
private let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
VStack(spacing: 0) {
content
.padding(16)
}
.background(.white)
.cornerRadius(14)
.shadow(color: .black.opacity(0.07), radius: 12, x: 0, y: 2)
}
}
I would like to animate any size changes to content
, but I can’t find a nice way of doing this. I found two ways that work:
- Using
animation(.linear)
inCardView
works, but is deprecated and discouraged since I have novalue
to attach the animation to. - Using
withAnimation
insidecontent
when changing the content works, too, but I would like to encapsulate this behaviour inCardView
.CardView
is heavily reused and doing it incontent
is easy to forget and also not where this behaviour belongs in my opinion.
I also tried using GeometryReader
but could not find a good way of doing it.
2
Answers
Here is an approach for you:
You may take look at this link as well:
How to replace deprecated .animation() in SwiftUI?
You might find this useful.
It uses a looping animation and a user gesture for add size and resting.