我正在使用 SwiftUI 为列表中的展开和折叠设置动画。
我怎样才能让部分的高度扩展像在带有 tableview 的 UIKit 中一样平滑地动画?
struct Rows: View {
let rows = ["Row 1", "Row 2", "Row 3", "Row 4", "Row 5"]
var body: some View {
Section {
ForEach(rows.identified(by: \.self)) { name in
Text(name)
.lineLimit(nil)
}
}
}
}
struct Header: View {
@State var isExpanded: Bool = false
var body: some View {
VStack(alignment: .leading) {
Button(action: {
self.isExpanded.toggle()
}) {
Text(self.isExpanded ? "Collapse Me" : "Expand Me")
.font(.footnote)
}
if self.isExpanded {
Rows().animation(.fluidSpring())
}
}
}
}
struct ContentView : View {
var body: some View {
List(0...4) { _ in
Header()
}
}
}
动画似乎只适用于行中的文本,而不是实际高度或分隔线为适应新行而增长。行文本似乎也从行的最顶部开始动画,而不是它出现在 View 层次结构中的位置。我需要一个流畅的动画。
最佳答案
我是这样实现的:(它带有适当的动画)
struct ExpandCollapseList : View {
@State var sectionState: [Int: Bool] = [:]
var body: some View {
NavigationView {
List {
ForEach(1 ... 6, id: \.self) { section in
Section(header: Text("Section \(section)").onTapGesture {
self.sectionState[section] = !self.isExpanded(section)
}) {
if self.isExpanded(section) {
ForEach(1 ... 4, id: \.self) { row in
Text("Row \(row)")
}
}
}
}
}
.navigationBarTitle(Text("Expand/Collapse List"))
.listStyle(GroupedListStyle())
}
}
func isExpanded(_ section: Int) -> Bool {
sectionState[section] ?? false
}
}
关于SwiftUI 动画列表行的展开和折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56802510/