Swift UI 菜单栏扩展:将第二个窗口置于前台

4
我正在开发一个MenuBar应用程序,并希望添加第二个窗口作为设置窗口。第二个窗口应该在点击MenuBar应用程序中的按钮后出现。我已经让窗口工作了,但它在其他窗口后面,并且我还在控制台上收到了这个警告:
[Window] Warning: Window SwiftUI.AppKitWindow 0x7fb562f0dcb0 ordered front from a non-active application and may order beneath the active application's windows.

我的应用程序文件:

import SwiftUI
import SceneKit

@main
struct pp: App {
    
    init() {
    }
    
    var body: some Scene {
        MenuBarExtra(content: {
            ContentView()
        }, label: {
            Text("something")
        })
        .menuBarExtraStyle(.window)
        
        Window("Settings", id: "settings-window") {
            VStack {
                Text("Some Text ...")
            }
            .frame(width: 350, height: 250)
        }.windowResizability(.contentSize)
        
    }
}

以下是与之相关的 ContentView.swift 部分:

import SwiftUI
import SceneKit

struct ContentView: View {
    @Environment(\.openWindow) var openWindow

    var body: some View {
        // ...

        Button(action: {
            openWindow(id: "settings-window")
        }, label: {
            Image(systemName: "gear")
        })

        // ...
    }
}

那么我该如何通过编程将设置窗口置于前台呢?


我遇到了同样的问题,但是我打开窗口的方式有点不同。我发现如果我能够访问到NSWindow实例,我可以调用window?.orderFrontRegardless(),然后新窗口就会出现在我想要的位置上方。 - Darrell Brogdon
1个回答

0

帮助我的是在 openWindow() 命令之前插入 NSApplication.shared.activate(ignoringOtherApps: true)。所以请尝试以下方式:

import SwiftUI
import SceneKit

struct ContentView: View {
    @Environment(\.openWindow) var openWindow

    var body: some View {
        // ...

        Button(action: {
            NSApplication.shared.activate(ignoringOtherApps: true)
            openWindow(id: "settings-window")
        }, label: {
            Image(systemName: "gear")
        })

        // ...
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接