当 ForEach 循环的元素出现或消失时,有什么方法可以添加动画?
我曾尝试以多种方式使用 withAnimation{} 和 .animation() 但它们似乎不起作用
这是一些代码(Xcode 11 beta 5):
import SwiftUI
struct test: View {
@State var ContentArray = ["A","B","C"]
var body: some View {
ScrollView{
VStack{
ForEach(ContentArray.indices, id: \.self){index in
ZStack{
// Object
Text(self.ContentArray[index])
.frame(width:100,height:100)
.background(Color.gray)
.cornerRadius(20)
.padding()
//Delete button
Button(action: {
self.ContentArray.remove(at: index)
}){
Text("?")
.foregroundColor(.white)
.frame(width:40,height:40)
.background(Color.red)
.cornerRadius(100)
}.offset(x:40,y:-40)
}
}
}
}
}
}
#if DEBUG
struct test_Previews: PreviewProvider {
static var previews: some View {
test()
}
}
#endif
Run Code Online (Sandbox Code Playgroud)
如下所示,没有动画,一切都感觉非常突然。任何解决方案都非常感谢
重要提示:当元素数量发生变化时,布局应该以与 …
我正在尝试创建一个非常简单的过渡动画,通过点击一个按钮在屏幕中央显示/隐藏一条消息:
struct ContentView: View {
@State private var showMessage = false
var body: some View {
ZStack {
Color.yellow
VStack {
Spacer()
Button(action: {
withAnimation(.easeOut(duration: 3)) {
self.showMessage.toggle()
}
}) {
Text("SHOW MESSAGE")
}
}
if showMessage {
Text("HELLO WORLD!")
.transition(.opacity)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据.transition(.opacity)动画文件
插入时从不透明过渡到不透明,移除时从不透明过渡到透明。
消息应该在showMessagestate属性为true 时淡入,在state属性为false时淡出。就我而言,这是不正确的。该消息以淡入淡出的动画显示,但它完全没有动画隐藏。有任何想法吗?
编辑:请参阅下面的gif从模拟器中获取的结果。