Preventing SwiftUI Frame Size Changes from Affecting Window Size in a macOS App

19 views Asked by At

I'm developing a macOS app using SwiftUI and have encountered a situation where adjusting the frame size of a SwiftUI View (specifically, a Rectangle) dynamically with a Slider causes the window size to change accordingly.

My app requires a variable window size that adapts to content, but I need the window size to remain unaffected by specific internal view size adjustments.

Common solutions like placing the view within a fixed size container or making the fixed window size explicitly aren't viable for my needs.

Thanks.

Here's a simplified version of sample:

import SwiftUI

struct ContentView: View {
    @State private var rectWidth: CGFloat = 100

    var body: some View {
        VStack {
            Rectangle()
                .frame(width: rectWidth, height: 100)
                .foregroundColor(.blue)
            Slider(value: $rectWidth, in: 50...2000)
                .padding()
        }
    }
}

video

1

There are 1 answers

0
Hajime On

Using GeometryReader solved the problem.

   import SwiftUI
    
    struct ContentView: View {
        @State private var rectWidth: CGFloat = 100
    
        var body: some View {
            GeometryReader { geometry in
                VStack {
                    Rectangle()
                        .frame(width: rectWidth, height: 100)
                        .foregroundColor(.blue)
                    Slider(value: $rectWidth, in: 50...2000)
                        .padding()
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
        }
    }