I'm new to Swift and I've been trying to build an app and learn as I go. I have a NavigationView that holds a List as a sidebar that renders the content as the user clicks. The bar between these two panes can be grabbed to allow the user to resize. This seems to be the default behavior of a NavigationView. I'm trying to find a way to disable it because I don't want the user to resize the sidebar.
struct Sidebar: View {
var body: some view {
List {
NavigationLink("First section", destination: FirstSection)
}
.frame(minWidth: 150, maxWidth: 150)
}
}
I also couldn't find a way to tell Swift that I want my List view to have a dynamic width that just fits the content. Just like it's done with CSS width: fit-content;
In the picture below, you can see that I was able to resize the sidebar to be almost half the screen. How to disable this behavior?
I do found a solution for that all you have to do is to set the destination width so that the sidebar can't be resized to the destination view for example like that ## consider the firstSection() as a View ##
Here the app main start
import SwiftUI
@main
struct macosTestApp: App {
var body: some Scene {
WindowGroup {
NavigationView {
SideBar()
}.toolbar {
// add the open/close sidebar navigation here
ToolbarItem(placement: .navigation) {
Button(action: toggleSidebar, label: { // 1
Image(systemName: "sidebar.leading")
})
}
}.frame(minWidth: 800, maxWidth: .infinity, minHeight: 600, maxHeight: .infinity, alignment: .center)
}
}
private func toggleSidebar() { // 2
NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}
}
Here the sidebar and the navigationView
import SwiftUI
struct SideBar: View {
@State var isActiveView:Bool = true
var body: some View {
List {
NavigationLink("First section", destination: FirstSection().frame(minWidth: 750, maxWidth: .infinity, minHeight: 600, maxHeight: .infinity, alignment: .center),isActive: $isActiveView)
}
}
}
struct FirstSection: View {
var body: some View {
Text("Hello")
}
}
struct text_Previews: PreviewProvider {
static var previews: some View {
SideBar()
}
}