等长矩形的动画不同?

时间:2020-05-20 14:40:58

标签: 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块中时,它似乎是从上到下绘制的。发生了什么事?

1 个答案:

答案 0 :(得分:1)

如果您找到一种方法使它们朝一个方向动画(而不是考虑为什么 怎么可能),那么这里是一个解决方案

通过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)
    }
}