安全区域不会延伸到透明标题栏下方。您可以使用edgesIgnoringSafeArea 告诉您的内容视图边缘忽略安全区域。类似于您的示例的东西:
struct ContentView: View {
var body: some View {
HStack(spacing: 0) {
Text("Hello, World!")
.frame(maxWidth: 200, maxHeight: .infinity)
.background(Color.red)
Text("Hello, World!")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
}.edgesIgnoringSafeArea(.all)
}
}
更新:
如果您想使用 NavigationView,您还必须在其内容中添加 edgesIgnoringSafeArea:
struct ContentView: View {
var body: some View {
NavigationView {
Text("Hello, World!")
.frame(maxWidth: 200, maxHeight: .infinity)
.background(Color.red)
.edgesIgnoringSafeArea(.all)
Text("Hello, World!")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
.edgesIgnoringSafeArea(.all)
}.edgesIgnoringSafeArea(.all)
}
}
不幸的是,此时它最初会显示一个标题栏,显然直到您强制重绘整个窗口。一旦将窗口移动到不同的显示或隐藏并再次显示,标题栏就会消失。所以,我的猜测是,这将在某个时候得到解决。
现在,您可以通过添加以编程方式强制隐藏和显示
DispatchQueue.main.async {
self.window.orderOut(nil)
self.window.makeKeyAndOrderFront(nil)
}
在window.makeKeyAndOrderFront(nil) 之后applicationDidFinishLaunching。然而,它将添加一个非常短的动画。如果它困扰您,您可以使用 NSWindow.animationBehavior 或类似的东西将其关闭。
更新 2:显然,如果您删除初始的 window.makeKeyAndOrderFront(nil) 并将其替换为上面的调度队列逻辑,它将不会动画。所以最后你会有
func applicationDidFinishLaunching(_ aNotification: Notification) {
let contentView = ContentView()
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView, .texturedBackground],
backing: .buffered, defer: false)
window.titlebarAppearsTransparent = true
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
// window.makeKeyAndOrderFront(self) <- don't call it here
DispatchQueue.main.async {
self.window.orderOut(nil)
self.window.makeKeyAndOrderFront(nil)
}
}