受到MScottWaller的答案启发,我为详细视图的最小尺寸添加了一些计算。这似乎将侧边栏固定在220到380之间。在macOS 126.1 / Xcode 14.0.1上运行。
关键部分是private func minDetailWidth()
struct ItemListView: View {
struct ItemRow: View {
struct ItemView: View {
let item: Item
var body: some View {
VStack {
Image(systemName: item.imageName)
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 2))
.padding(2)
.overlay(Circle().strokeBorder(Color.black.opacity(0.1)))
.shadow(radius: 3)
.padding(4)
Text(item.name)
.font(.largeTitle)
}
}
}
let item: Item
var body: some View {
NavigationLink(destination: ItemView(item: item)) {
HStack {
Image(systemName: item.imageName)
.resizable()
.frame(width: 50, height: 50)
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 2))
.padding(2)
.overlay(Circle().strokeBorder(Color.black.opacity(0.1)))
.shadow(radius: 3)
.padding(4)
Text(item.name)
.font(.largeTitle)
}
}
}
}
let items: [Item]
var body: some View {
List(items) { fruit in
ItemRow(item: fruit)
}
}
}
struct Item: Identifiable {
let id = UUID()
let name: String
let imageName: String
let color: Color
}
class Model: ObservableObject {
@Published var transportation: [Item] = loadTransportation()
@Published var vegetables: [Item] = loadVegetables()
static func loadTransportation() -> [Item] {
return [
Item(name: "Airplane", imageName: "airplane", color: .orange),
Item(name: "Car", imageName: "car", color: .blue),
Item(name: "Bus", imageName: "bus.fill", color: .red),
Item(name: "Tram", imageName: "tram.fill", color: .pink),
Item(name: "Ferry", imageName: "ferry", color: .purple),
Item(name: "Bicycle", imageName: "bicycle", color: .green),
]
}
static func loadVegetables() -> [Item] {
return [
Item(name: "Spinach", imageName: "spinach", color: .red),
Item(name: "Lettuce", imageName: "lettuce", color: .orange),
Item(name: "Tomatoes", imageName: "tomatoes", color: .green),
Item(name: "Onion", imageName: "onion", color: .blue),
]
}
}
@ObservedObject private var model = Model()
private var sideBarMaxWidth = 380.0
private func minDetailWidth(_ proxy: GeometryProxy) -> Double {
let rv_ = proxy.size.width - sideBarMaxWidth
let rv = max(rv_, 480)
return rv
}
var body: some View {
GeometryReader { proxy in
NavigationView {
List {
NavigationLink(
"Fruits",
destination:
ItemListView(items: self.model.transportation)
.frame(minWidth: minDetailWidth(proxy), idealWidth: 840, maxWidth: .infinity)
)
NavigationLink(
"Vegetables",
destination:
ItemListView(items: self.model.vegetables)
.frame(minWidth: minDetailWidth(proxy), idealWidth: 840, maxWidth: .infinity)
)
}
.frame(minWidth: 220, maxWidth: sideBarMaxWidth)
Text("Nothing Selected")
.frame(minWidth: minDetailWidth(proxy), maxWidth: .infinity)
}
}
}
}
struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
.environment(\.colorScheme, .light)
ExampleView()
.environment(\.colorScheme, .dark)
}
}