HStack size change animation issue: When I tap on a rectangle to increase its size, the rectangle animates, but the parent HStack doesn’t animate its layout to accommodate the increased size of the child view. I want the parent HStack to smoothly animate its size adjustment when the size of its child changes.
import SwiftUI
struct ContentView: View {
@State private var array1: [CustomType] = [CustomType(value: 1, color: .red), CustomType(value: 2, color: .red), CustomType(value: 3, color: .red)]
var body: some View {
VStack {
Spacer()
MyHstackView(array: $array1)
Spacer()
}
.padding()
}
}
struct MyHstackView: View {
@Binding var array: [CustomType]
var body: some View {
HStack {
ForEach($array) { item in
RectangleView(item: item)
}
}
.padding()
.background(Rectangle().strokeBorder(.black, lineWidth: 1.0))
.background(Color.yellow)
}
}
struct RectangleView: View {
@Binding var item: CustomType
var body: some View {
Rectangle()
.fill(item.color)
.frame(width: item.rect.size.width, height: item.rect.size.height)
.overlay(Rectangle().strokeBorder(.black, lineWidth: 1.0))
.gesture(tapGesture)
.animation(.linear(duration: 1.0), value: item.rect.size)
}
private var tapGesture: some Gesture {
return TapGesture(count: 1)
.onEnded {
item.rect.size.width += 20.0
}
}
}
struct CustomType: Identifiable {
init(value: Int, color: Color, initializeSize: CGSize = CGSize(width: 100.0, height: 100.0)) {
self.value = value
self.color = color
self.rect = CGRect(origin: .zero, size: initializeSize)
}
let id: UUID = UUID()
var value: Int
var color: Color
var rect: CGRect
}