我正在为一个包含NavigationView的Mac应用程序使用SwiftUI,其中NavigationView包含侧边栏列表。当选择侧边栏中的项目时,它会更改在详细视图中显示的视图。详细视图中呈现的视图具有不同的大小,这应该导致在显示它们时窗口的大小发生变化。然而,当详细视图的大小发生变化时,窗口不会随之自动调整大小以适应新的详细视图。
如何使窗口大小根据NavigationView的大小变化而变化?
以下是我创建此应用程序的示例代码:
如何使窗口大小根据NavigationView的大小变化而变化?
以下是我创建此应用程序的示例代码:
import SwiftUI
struct View200: View {
var body: some View {
Text("200").font(.title)
.frame(width: 200, height: 400)
.background(Color(.systemRed))
}
}
struct View500: View {
var body: some View {
Text("500").font(.title)
.frame(width: 500, height: 300)
.background(Color(.systemBlue))
}
}
struct ViewOther: View {
let item: Int
var body: some View {
Text("\(item)").font(.title)
.frame(width: 300, height: 200)
.background(Color(.systemGreen))
}
}
struct DetailView: View {
let item: Int
var body: some View {
switch item {
case 2:
return AnyView(View200())
case 5:
return AnyView(View500())
default:
return AnyView(ViewOther(item: item))
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
List {
ForEach(1...10, id: \.self) { index in
NavigationLink(destination: DetailView(item: index)) {
Text("Link \(index)")
}
}
}
.listStyle(SidebarListStyle())
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
当详细视图大小发生更改时,示例应用程序的外观如下:
let window = NSApp.mainWindow
来获取对AppDelegate中窗口的引用。那只是为了获得框架 - NotificationCenter代码并不关心ResizingView
在哪里使用 - 您可以将其正常嵌入SwiftUIWindowGroup
(或层次结构中的任何其他位置)。感谢Asperi提供如此好的答案! - Dominic Holmes