In the following code, I have a simple button that toggles the appearance of a rectangle between two elements in a VStack
.
When this toggle happens, the enclosing NSWindow
changes size immediately and then the contents changes with the animation.
A side effect is that the "Hello, World" Text
appears to move in and out of place (where I would hope that the Text
would stay anchored to the top).
Is there a way that I can do the following (with animation) where the Text
element stays anchored at the top of the View
and doesn't move while the rectangle comes into place and the Button
slides down/up to accommodate the rectangle?
struct ContentView: View {
var body: some View {
Button("Show window") {
let window = NSWindow()
window.styleMask = [.titled, .closable]
window.contentView = NSHostingView(rootView: WindowContent())
window.makeKeyAndOrderFront(nil)
window.center()
}
.padding()
}
}
struct WindowContent: View {
@State private var showRectangle = false
var body: some View {
VStack {
Text("Hello, world")
if showRectangle {
Rectangle().fill(Color.red)
.frame(height: 100)
.frame(maxWidth: .infinity)
}
Button(action: {
withAnimation(.linear(duration: 3)) {
showRectangle.toggle()
}
}) {
Text("Toggle")
}
}
.fixedSize()
.padding(20)
}
}