Home > Back-end >  How to keep newly opened macOS window in front & prevent being hidden with SwiftUI?
How to keep newly opened macOS window in front & prevent being hidden with SwiftUI?

Time:10-21

I am using SwiftUI to create a macOS app and need to create a new window that opens with an image inside of it, which I am successfully accomplishing currently.

However, if I click back on the main app window, the newly opened window goes to the background and is hidden (normal behavior), however, I want the newly opened window to always be on top of the main app window AFTER if I click back on the main application window.

The reason is that the new window (WindowGroup) opened contains an image with the information I need to enter in the main app so if it goes behind the main app window, I can't see the image anymore.

Is there a WindowGroup modifier I can implement so that after the WindowGroup("imageView") window opens, it is always on top & how can I integrate into my existing code?

Thank you!

@main
struct customApp: App {
    @StateObject var session = SessionStore()
    
    var body: some Scene {
        WindowGroup("mainView") {
            ContentView().environmentObject(session)
        }.handlesExternalEvents(matching: ["mainView"])
        
        WindowGroup("imageView") {
            ImageView(url: SessionStore.imageUrl)
        }.handlesExternalEvents(matching: ["imageView"])
    }
}

View that opens new window

struct ImageViews: View {
    @Environment(\.openURL) var openURL
    
    var body: some View {
        HStack {
            WebImage(string: idUrl)
                .onTapGesture {
                    guard let url = URL(string: "app://imageView") else { return }
                    openURL(url)
                }
        }
    }
}

CodePudding user response:

Set the window.level to always on top .floating. You can access it via NSApplication.shared.windows.

            Button("Window level") {
            for window in NSApplication.shared.windows {
                window.level = .floating
            }
        }
  • Related