如何为视图外观设置动画?

我有一个自定义视图。它用作列表视图中的单元格。我想为 quote.expanded = true 上的Group子视图的外观设置动画(例如,褪色)。

.animation(.default)修饰符不起作用。

apply_async
jzym123 回答:如何为视图外观设置动画?

使用过渡对视图外观进行动画处理

https://developer.apple.com/tutorials/swiftui/animating-views-and-transitions

https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-and-remove-views-with-a-transition

,

以下代码为我制作了动画。请注意,列表中的动画虽然可能仍然比没有动画要好,但仍然看起来有些怪异。这是因为列表行本身的高度不设置动画,而是捕捉到其最终高度,而行内的视图却设置了动画。这是一个SwiftUI问题,除了file feedback之外,您目前无法对此做任何事情。

struct StackOverflowTests: View {
    @State private var array = [QuoteDataModel(),QuoteDataModel(),QuoteDataModel()]

    var body: some View {
        List {
            ForEach(array.indices,id: \.self) { index in
                QuoteView(quote: self.array[index])
                    .onTapGesture { self.array[index].expanded.toggle() }
            }
        }
    }
}

struct QuoteView: View {

    var quote : QuoteDataModel

    var body: some View {
        VStack(alignment: .leading,spacing: 5) {
            Text(quote.latin)
                .font(.title)
            if quote.expanded {
                Group() {
                    Divider()
                    Text(quote.russian).font(.body)
                }
            }
        }
        .animation(.default)
    }
}
,

尝试这个。...但是您会看到还有其他问题,因为文本保持左对齐...

var body:某些视图{

    VStack(alignment: .leading,spacing: 5) {
        Button("Tap me") {
            withAnimation() {

                self.expanded.toggle()
                if self.expanded {
                    self.opacity = 1
                } else {
                    self.opacity = 0
                }
            }

        }
        Text("aha")
            .font(.title)
        if expanded {
            Group() {
                Divider()
                Text("oho").font(.body)
            }.opacity(opacity)
        }
    }
}
本文链接:https://www.f2er.com/3117636.html

大家都在问