Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How to properly animate content size change inside List?

Tags:

ios

swift

swiftui

import SwiftUI

struct DynamicRectangle: View {
    @State private var isExpanded = false

    var body: some View {
        Rectangle()
            .fill(Color.blue)
            .frame(width: 200, height: isExpanded ? 400 : 200)
            .animation(.spring())

        .onTapGesture {
            self.isExpanded.toggle()
        }
    }
}

struct ContentView: View {

    var body: some View {
        List {
            DynamicRectangle()
            DynamicRectangle()
            DynamicRectangle()
        }
    }
}

Here is a tiny example that still has an obvious problem: though the size changes are smoothly animating, the List itself immediately changes its row size. Is there any workaround to make it animate the row size together with the content size I have inside?

Thanks!

like image 820
totsamyzed Avatar asked Oct 16 '22 09:10

totsamyzed


1 Answers

When I use a ScrollView it works perfectly fine:

import SwiftUI

struct DynamicRectangle: View {
    @State private var isExpanded = false

    var body: some View {
        Rectangle()
            .fill(Color.blue)
            .frame(width: 200, height: isExpanded ? 400 : 200)
            .animation(.spring())

        .onTapGesture {
            self.isExpanded.toggle()
        }
    }
}

struct ContentView: View {

    var body: some View {
        ScrollView {
            DynamicRectangle()
            DynamicRectangle()
            DynamicRectangle()
        }
    }
}

I prefer ScrollView over List.

like image 136
krjw Avatar answered Oct 19 '22 02:10

krjw