首页 > 解决方案 > NSWindow contentView 不覆盖整个窗口大小 - macOS 和 SwiftUI

问题描述

我正在使用 SwiftUI 启动一个新的 macOS 应用程序,但我遇到了一个大问题。该应用程序需要全尺寸contentView(下方titleBar),但我无法完成。在使用 Storyboards 的新项目上工作正常,但使用 SwiftUI 则不行。

我的代码: 在此处输入图像描述

结果: 在此处输入图像描述

它应该是这样的: 在此处输入图像描述

有任何想法吗?谢谢!

标签: macosswiftuifullscreennswindowtitlebar

解决方案


我只是在中使用了以下变体AppDelegate,的内容ContentView和其他的可以是任何

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()
        .edgesIgnoringSafeArea(.top) // to extend entire content under titlebar 

    // Create the window and set the content view. 
    window = NSWindow(
        contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
        styleMask: [.titled, .closable, .miniaturizable, .texturedBackground, .resizable, .fullSizeContentView],
        backing: .buffered, defer: false)
    window.center()
    window.setFrameAutosaveName("Main Window")

    window.titlebarAppearsTransparent = true // as stated
    window.titleVisibility = .hidden         // no title - all in content

    window.contentView = NSHostingView(rootView: contentView)
    window.makeKeyAndOrderFront(nil)
}

推荐阅读