Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set width of SidebarView in macOS using SwiftUI

Tags:

macos

swiftui

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.

like image 370
wigging Avatar asked Apr 30 '20 13:04

wigging


1 Answers

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.

like image 156
MScottWaller Avatar answered Nov 14 '22 19:11

MScottWaller