SwiftUI animating expand and collapse of list rows

后端 未结 3 1916
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 00:39

I\'m using SwiftUI to animate an expand and collapse in a list.

How can I get the height expansion of the section to animate smoothly like it would in UIKit with a table

3条回答
  •  天涯浪人
    2021-02-06 01:07

    try to implement it like this:

    struct ContentView : View {
    
        @State var expanded:[Int:Bool] = [:]
    
        func isExpanded(_ id:Int) -> Bool {
            expanded[id] ?? false
        }
    
        var body: some View {
            NavigationView{
                List {
                    ForEach(0...80) { section in
                        Section(header: CustomeHeader(name: "Section \(section)", color: Color.white).tapAction {
                            self.expanded[section] = !self.isExpanded(section)
                        }) {
                            if self.isExpanded(section) {
                                ForEach(0...30) { row in
                                    Text("Row \(row)")
                                }
                            }
                        }
                    }
                }
            }.navigationBarTitle(Text("Title"))
        }
    }
    
    struct CustomeHeader: View {
        let name: String
        let color: Color
    
        var body: some View {
            VStack {
                Spacer()
                HStack {
                    Text(name)
                    Spacer()
                }
                Spacer()
                Divider()
            }
            .padding(0)
                .background(color.relativeWidth(1.3))
                .frame(height: 50)
        }
    }
    

提交回复
热议问题