ios - 相等的矩形动画不同?

标签 ios swift swiftui

import SwiftUI

struct GrowView: View {
    var size:CGFloat = 400
    @State var scale:CGFloat = 0
    var body: some View {
        HStack(alignment: .bottom) {
            Rectangle()
                .foregroundColor(.red)
                .frame(height: 300 * scale)
                .animation(.default)
            if true {
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 400 * scale)
                    .animation(.default)
            }

        }.onAppear {
            self.scale = 1
        }.frame( maxHeight: 500, alignment: .bottom)
    }
}

struct GrowView_Previews: PreviewProvider {
    static var previews: some View {
        GrowView()
    }
}

没有 if块,第二个 Rectangle从下到上动画。当它在 If 内时然而,块似乎是从上到下绘制的。这是怎么回事?

最佳答案

如果你找到一种方法让它们朝着一个方向动画(而不是思考为什么和如何)那么这里是一个解决方案

使用 Xcode 11.4/iOS 13.4 测试

    var body: some View {
        HStack(alignment: .bottom) {
            Rectangle()
                .foregroundColor(.red)
                .frame(height: 300 * scale)
//                .animation(.default)   // XX remove !!
            if true {
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 400 * scale)
//                    .animation(.default) // XX remove !!
            }

        }
        .animation(.default)       // << put animation here !!!
        .onAppear {
            self.scale = 1
        }.frame( maxHeight: 500, alignment: .bottom)
    }

更新:有条件的第二个矩形延迟的解决方案
struct GrowView: View {
    var size:CGFloat = 400
    @State var scale:CGFloat = 0
    @State var showSecond = true

    var body: some View {
        HStack(alignment: .bottom) {
            Rectangle()
                .foregroundColor(.red)
                .frame(height: 300 * scale)
                .animation(.default)
            VStack {
                if showSecond {
                    Rectangle()
                        .foregroundColor(.red)
                        .frame(height: 400 * scale)
                }
            }
            .animation(Animation.default.delay(0.5))
        }
        .onAppear {
            self.scale = 1
        }.frame(maxHeight: 500, alignment: .bottom)
    }
}

关于ios - 相等的矩形动画不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61915925/

相关文章:

ios - iPad 的 Xcode 7 Storyboard问题

ios - 如何防止额外的触摸干扰拖动位置

ios - 为自定义 UIButton 设置禁用状态

SwiftUI:内容是图像的 ViewModifier

swift - 在 SwiftUI 类中调用包装的 UIViewController 函数时获取 nil

iphone - 付款被拒绝。请在您的计算机上为此金额添加有效的付款方式。 (iOS 中的 PayPal 实时模式)

ios - 无法在 iPhone XS 和 iPhone XS Max 上缩放 Assets 以保持一致性

ios - 从异步任务加载 UITableViewController 中的值

ios - 在 SwiftUI 中拖动分隔符

ios - Xamarin iOS - 是否可以将 "Unified- Single View"项目定位到 iOS 6.x?