简体   繁体   English

SwiftUI:如何正确动画列表内的内容大小变化?

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

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.这是一个仍然存在明显问题的小例子:虽然大小变化是平滑的动画,但 List 本身会立即改变它的行大小。 Is there any workaround to make it animate the row size together with the content size I have inside?是否有任何解决方法可以将行大小与我内部的内容大小一起设置为动画?

Thanks!谢谢!

When I use a ScrollView it works perfectly fine:当我使用ScrollView时,它工作得非常好:

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 .我更喜欢ScrollView而不是List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM