我有问题动画在SwiftUI,如果我使用.animation我的动画不工作.

ZStack(alignment: .bottom) {
            VStack {
                Button("Button") {
                    showView.toggle()
                }
                
                Spacer()
            }
            
            if showView {
                RoundedRectangle(cornerRadius: 30)
                    .frame(height: UIScreen.main.bounds.height * 0.5)
                    .transition(.move(edge: .bottom))
                    .animation(.easeInOut, value: showView)
            }
        }
        .ignoresSafeArea(edges: .bottom)

但是,如果我在我的按钮中使用了with Animation,并且删除了.Animation或保留它,它就可以工作了.

ZStack(alignment: .bottom) {
            VStack {
                Button("Button") {
                    withAnimation {
                        showView.toggle()
                    }
                }
                
                Spacer()
            }
            
            if showView {
                RoundedRectangle(cornerRadius: 30)
                    .frame(height: UIScreen.main.bounds.height * 0.5)
                    .transition(.move(edge: .bottom))
                    .animation(.easeInOut, value: showView)
            }
        }
        .ignoresSafeArea(edges: .bottom)

有人能给我解释一下这是怎么用的吗?我正在try DispatchQueue.main.async,它仍然是一样的.

推荐答案

你定义了两种不同的状态:

  1. 如果showView = true,则为RoundedRectangle
  2. 如果showView = false,则没有RoundedRectangle

所以,每次showView改变,body将被重新渲染.如果它在false - true之间切换,那么RoundedRectangle将立即显示,没有任何动画,因为它直到showView = true才出现.如果它在真-假之间切换,那么它就可以用动画来消除,因为现在,它是视图的一部分.你可以try 这样做,使它更顺利地显示/消失:

ZStack(alignment: .bottom) {
    VStack {
        Button("Button") {
            showView.toggle()
        }

        Spacer()
    }

    RoundedRectangle(cornerRadius: 30)
        .frame(height: showView ? (UIScreen.main.bounds.height * 0.5) : 0)
        .transition(.move(edge: .bottom))
        .animation(.easeInOut, value: showView)
}
.ignoresSafeArea(edges: .bottom)

Swift相关问答推荐

如何在SWIFT中轻松格式化公制和英制使用的UnitVolume

如何将CodingKeys作为数组而不是枚举传递到类外部的函数中?

SWIFT计划计时器方法在时间间隔后未被调用

不能将符合协议的SWIFT类的实例分配给需要该协议的Objective-C属性

如何在SWIFT Memory中处理对VAR数组的更新(对COW感到困惑)

如何在SwiftUI中做出适当的曲线?

';NSInternal不一致异常';,原因:';可见导航栏Xcode 15.0 Crash请求布局

ToolbarItem 包含在动画中但不应该包含在动画中

Xcode创建GitHub仓库,但未推送所有文件

如何延迟 swift 属性 didSet 使其每秒只触发一次

是否可以使任何协议符合 Codable?

不使用 ViewController 时如何显示推送通知的alert 对话框

Apple 的自然语言 API 返回意外结果

临时添加到视图层次 struct 后,Weak view引用不会被释放

找不到接受提供的参数的/的重载

iOS Swift - 如何更改表格视图的背景 colored颜色 ?

使用 swift 运行 pod install 时出错

快速的 AES 加密

使用 JSONEncoder 对类型为 Codable 的变量进行编码

swift中的匿名类