Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can fix the size of view in mac in SwiftUI?

Tags:

swift

swiftui

I am experiencing a new change with Xcode Version 14.1 about view size in macOS, in older version if I gave a frame size or use fixedSize modifier, the view would stay in that size, but with 14.1 I see that view could get expended even if I use frame or fixedSize modifier, which is not what I expect. For example I made an example to show the issue, when I update the size to 200.0, the view/window stay in bigger size, which I expect it shrinks itself to smaller size, so how can I solve the issue?

 struct ContentView: View {
    
    @State private var sizeOfWindow: CGFloat = 400.0
    
    var body: some View {
        VStack {
            
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            
            Text("Hello, world!")
            
            Button("update", action: {
                
                if (sizeOfWindow == 200.0) { sizeOfWindow = 400.0 }
                else { sizeOfWindow = 200.0 }
                
                print(sizeOfWindow)
                
            })
        }
        .frame(width: sizeOfWindow, height: sizeOfWindow)
        .fixedSize()
    }
}
like image 461
ios coder Avatar asked Oct 22 '25 06:10

ios coder


1 Answers

Credit:

  • Credit to https://developer.apple.com/forums/thread/708177?answerId=717217022#717217022

Approach:

  • Use .windowResizability(.contentSize)
  • Along with windowResizability use one of the following:
    • if you want set size based on the content size use fixedSize()
    • If you want to hardcode the frame then directly set .frame(width:height:)

Code

@main
struct DemoApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .frame(width: 200, height: 200) //or use fixed size and rely on content
        }
        .windowResizability(.contentSize)
    }
}
like image 119
user1046037 Avatar answered Oct 24 '25 11:10

user1046037