小编mou*_*bat的帖子

在新窗口中打开视图的按钮 SwiftUI 5.3 for Mac OS X

我想要一个按钮来打开一个新窗口并在 SwiftUI for MacOS 中加载一个视图(用于应用程序的首选项),但我不确定正确的方法。

我尝试创建一个函数并从按钮操作调用它,但在关闭新窗口时应用程序崩溃:

线程 1:EXC_BAD_ACCESS(代码=1,地址=0x20)

这是我的功能:

func openPreferencesWindow() {
    var preferencesWindow: NSWindow!
    let preferencesView = PreferencesView()
    // Create the preferences window and set content
    preferencesWindow = NSWindow(
        contentRect: NSRect(x: 20, y: 20, width: 480, height: 300),
        styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
        backing: .buffered,
        defer: false)
    preferencesWindow.center()
    preferencesWindow.setFrameAutosaveName("Preferences")
    preferencesWindow.contentView = NSHostingView(rootView: preferencesView)
    preferencesWindow.makeKeyAndOrderFront(nil)
}
Run Code Online (Sandbox Code Playgroud)

这是我调用它的按钮:

Button(action: {
    openPreferencesWindow()
}) {
    Text("Preferences").font(.largeTitle).foregroundColor(.primary)
}
Run Code Online (Sandbox Code Playgroud)

我觉得应该在 AppDelegate 中构建窗口,但我不确定我会如何调用它。

macos window button nswindow swiftui

8
推荐指数
1
解决办法
2205
查看次数

SwiftUI 2.0 无法使用 NSViewRepresentable 从 NSWindow 上的 styleMask 中删除 .titled

我正在为 SwiftUI 2.0 重新设计我的应用程序,但在复制我可以使用 AppDelegate 执行的操作时遇到了问题。

我正在使用 NSViewRepresentable 来访问 NSWindow,这样我就可以删除窗口的标题栏(我知道它不在指南中,但永远不会提交)。.titled从 中删除时styleMask,应用程序崩溃。

struct WindowAccessor: NSViewRepresentable {
    @Binding var window: NSWindow?
    
    func makeNSView(context: Context) -> NSView {
        let view = NSView()
        DispatchQueue.main.async {
            self.window = view.window
            self.window?.isOpaque = false
            self.window?.titlebarAppearsTransparent = true
            self.window?.backgroundColor = NSColor.clear
            self.window?.styleMask = [.fullSizeContentView]
            self.window?.isMovableByWindowBackground = true
            self.window?.backingType = .buffered
        }
        return view
    }
    
    func updateNSView(_ nsView: NSView, context: Context) {}
}

@main
struct MyApp_App: App {
    @State private var window: NSWindow?
    var body: …
Run Code Online (Sandbox Code Playgroud)

macos nswindow swiftui nsviewrepresentable

6
推荐指数
0
解决办法
282
查看次数

标签 统计

macos ×2

nswindow ×2

swiftui ×2

button ×1

nsviewrepresentable ×1

window ×1