【问题标题】:How make animations work inside ScrollView in SwiftUI? Accordion style animation in SwiftUI如何在 SwiftUI 的 ScrollView 中制作动画? SwiftUI 中的手风琴风格动画
【发布时间】:2019-09-23 07:08:27
【问题描述】:

我正在尝试使用 SwiftUI 构建带有动画的手风琴样式视图。但是,如果我将其包装到 ScrollView 中,动画将无法正常工作。下面是我正在尝试解决的代码。

struct ParentView: View {
    @State var isPressed = false
    var body: some View {
        GeometryReader { geometry in
            ScrollView {
                Group {
                    SampleView(index: 1)
                    SampleView(index: 2)
                    SampleView(index: 3)
                    SampleView(index: 4)
                }.border(Color.black).frame(maxWidth: .infinity)
            }.border(Color.green)
        }
    }
}

struct SampleView: View {
    @State var index: Int
    @State var isPressed = false
    var body: some View {
        Group {
            HStack(alignment:.top) {
                VStack(alignment: .leading) {
                    Text("********************")
                    Text("This View = \(index)")
                    Text("********************")
                }
                Spacer()
                Button("Press") { self.isPressed.toggle() }
            }

            if isPressed {
                VStack(alignment: .leading) {
                    Text("********************")
                    Text("-----> = \(index)")
                    Text("********************")
                }.transition(.slide).animation(.linear).border(Color.red)
            }
        }

    }
}

下面是我面临的问题的屏幕截图。

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    要使其具有动画效果,请将 self.isPressed.toggle() 包裹在 withAnimation 闭包中。

    Button("Press") { withAnimation { self.isPressed.toggle() } }
    

    【讨论】:

    • 是的,你是对的,但是当我这样做时,我的视图向上推,我的第一行在屏幕上的可见区域后面,正如您在我附加的第二个屏幕截图中看到的那样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2023-03-31
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多