2

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)
                }
        }
    }
}

1 Answer 1

3

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Where would I put that in my existing code? It is not very clear to me.
This will set ALL windows to .floating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.