SwiftUI animating expand and collapse of list rows

后端 未结 3 1917
被撕碎了的回忆
被撕碎了的回忆 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 00:51

    I implemented it like this: (It is with proper animation)

    struct ExpandCollapseList : View {
        @State var sectionState: [Int: Bool] = [:]
    
        var body: some View {
            NavigationView{
                List{
                    ForEach(1...6){ section in
                        Section(header: Text("Section \(section)").onTapGesture {
                            self.sectionState[section] = !self.isExpanded(section)
                        }) {
                            if self.isExpanded(section){
                                ForEach(1...4){ row in
                                    Text("Row \(row)")
                                }
                            }
                        }
                    }
                }
                .navigationBarTitle(Text("Expand/Collapse List"))
                .listStyle(.grouped)
            }
        }
    
        func isExpanded(_ section:Int) -> Bool {
            sectionState[section] ?? false
        }
    }
    

提交回复
热议问题