I'm building a macOS 13 app using SwiftUI. The app has two-column navigation by using the NavigationSplitView
which gives a sidebar and detail view. The detail views are different sizes so I would like the window to change size based on the size of each detail view.
In the example below, the detail views are AppleView
, KiwiView
, and PeachView
. The AppleView
has a size of 400x300 and the KiwiView
is 300x200. When I run the app, the window does not adjust its size when the detail view changes. I tried to wrap the navigation view in a VStack
but that did not help. Does anyone know how I can get the app's window to adjust size based on the selected detail view?
import SwiftUI
struct AppleView: View {
var body: some View {
Text("Apple View ")
.font(.title)
.frame(width: 400, height: 300)
.background(.red)
}
}
struct KiwiView: View {
var body: some View {
Text("Kiwi View ")
.font(.title)
.frame(width: 300, height: 200)
.background(.green)
}
}
struct PeachView: View {
var body: some View {
Text("Peach View ")
.font(.title)
.background(.pink)
}
}
enum Fruit: String, CaseIterable {
case apple = "Apple"
case kiwi = "Kiwi"
case peach = "Peach"
}
struct ContentView: View {
@State private var selectedFruit: Fruit = .apple
var body: some View {
NavigationSplitView {
List(Fruit.allCases, id: \.self, selection: $selectedFruit) { fruit in
Text(fruit.rawValue)
}
} detail: {
switch selectedFruit {
case .apple:
AppleView()
case .kiwi:
KiwiView()
case .peach:
PeachView()
}
}
}
}
I also tried setting the .windowResizability()
of the main window group but that didn't fix the problem.
import SwiftUI
@main
struct ExampleApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.windowResizability(.contentSize)
}
}