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