【问题标题】:Animated Expand/Collapse group in horizontal ScrollView (SwiftUI)水平 ScrollView (SwiftUI) 中的动画展开/折叠组
【发布时间】:2021-11-01 15:42:59
【问题描述】:

我有一个简单的 ForEach 根据 expanded 标志显示 5 或 10 个 Text 视图。一切都包裹在一个水平的ScrollView 中,因为文本可能很长。 展开组时的动画看起来不错,但是当组折叠时有一个小的弹跳,视图会上下波动。如果我删除 ScrollView,这不会发生。知道什么会导致这种弹跳吗?

struct ContentView: View {
    @State var expanded = false
    let colors: [Color] = [.red, .green, .blue, .orange, .blue, .brown, .cyan, .gray, .indigo, .mint]
    var body: some View {
        VStack {
            ScrollView(.horizontal) {
                VStack(spacing: 20) {
                    ForEach(colors.prefix(upTo: expanded ? 10 : 5), id: \.self) { color in
                        Text(color.description.capitalized)
                    }
                }
            }
            Button("Expand/collapse") {
                expanded.toggle()
            }
            Spacer()
        }.animation(.easeIn(duration: 1))
    }
}

【问题讨论】:

  • 如果将bounces 设置为false 会发生什么?
  • @DVN-Anakin 一样 :(

标签: ios animation swiftui


【解决方案1】:

你需要为动画使用值:

struct ContentView: View {
    @State var expanded = false
    let colors: [Color] = [.red, .green, .blue, .orange, .blue, .red, .green, .blue, .orange, .blue]
    var body: some View {
        VStack {
            ScrollView(.horizontal) {
                VStack(spacing: 20) {
                    ForEach(colors.prefix(upTo: expanded ? 10 : 5), id: \.self) { color in
                        Text(color.description.capitalized)
                    }
                }
            }
            Button("Expand/collapse") {
                expanded.toggle()
            }
            Spacer()
        }.animation(.easeIn(duration: 1), value: expanded) // <<: Here!
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2019-01-09
    • 1970-01-01
    • 2017-02-21
    • 2011-09-12
    相关资源
    最近更新 更多