I'm using a NavigationView to display a SidebarView and DetailView in the window of a Mac app:
import SwiftUI
private let fruits = ["🍎 Apple", "🥥 Coconut", "🥭 Mango", "🥝 Kiwi"]
struct SidebarView: View {
@Binding var selectedFruit: String?
var body: some View {
List(fruits, id: \.self, selection: $selectedFruit) { fruit in
Text("\(fruit)")
}
.listStyle(SidebarListStyle())
.frame(minWidth: 180, idealWidth: 200, maxWidth: 300)
}
}
struct DetailView: View {
@Binding var fruit: String?
var body: some View {
Text("\(fruit ?? "Default Fruit")")
.font(.headline)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView: View {
@State private var selectedFruit: String?
var body: some View {
NavigationView {
SidebarView(selectedFruit: $selectedFruit)
DetailView(fruit: $selectedFruit)
}
.frame(width: 500, height: 400)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The width of the SidebarView can be adjusted by dragging the center divider left or right in the window. I would like to have an initial width of 200 defined for the sidebar along with a minimum width of 180 and a max width of 300. I attempted this by setting the frame of the List which does indeed set the max width but the sidebar can still be completely collapsed. Also, the initial width of the sidebar seems to be defined by minWidth
not idealWidth
.
For anyone who finds this and is wanting to know how to set the maxWidth of a sidebar in macOS, you really don't. If you do, the view will stop growing and then be caught in the middle of the sidebar, which will keep expanding.
It took me a minute to figure this out, but what you do is set the minWidth of the other view, the detail view. And the sidebar will grow until it can't. You'll notice that even the sidebar of Finder grows and grows until it hits the minWidth of the detail, so to speak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With