8

By default, an NSWindow that hosts a SwiftUI view will automatically resize to fit the size of the view if/when it changes. However, if the changes are animated, the window jumps to the final size without animating. Is there a way to animate the window size along with the content?

I've tried this with and without SwiftUI's lifecycle. I'v also tried calling the toggle method with NSAnimationContext.runAnimationGroup

Gif showing SwiftUI view animating but window jumping to final position without animating

struct ContentView: View {
    @State var isExpanded = false
    
    var body: some View {
        VStack {
            Button(isExpanded ? "Close" : "Open", action: toggleExpand)
            
            if isExpanded {
                ForEach(0..<5) { count in
                    Text("\(count). Some Item")
                }
            }
        }
        .padding()
        .fixedSize()
    }
    
    func toggleExpand() {
        withAnimation(.easeInOut(duration: 1)) { isExpanded.toggle() }
    }
}

0 Answers0