swiftPunk
swiftPunk

Reputation: 1

How can I make my Content View Window became borderless in SwiftUI for macOS?

I am using this code for making my Window became borderless, but all I am getting is crash in run time!

struct ContentView: View {
    var body: some View {
        Button("borderless") {
            NSApplication.shared.keyWindow?.styleMask = .borderless
        }
    }
}

Error:

Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)


From Xcode Help:

@note The styleMask can only be set on macOS 10.6 and later. Valid \c styleMask settings have the same restrictions as the \c styleMask passed to -initWithContentRect:styleMask:backing:defer:. Some \c styleMask changes will cause the view hierarchy to be rebuilt, since there is a different subclass for the top level view of a borderless window than for the top level view of a titled window.

Xcode version Version 14.1 (14B47b)

The goal is solving the error that using the code does not crash the app and not changing the question.

Upvotes: 2

Views: 1084

Answers (1)

Ranoiaetep
Ranoiaetep

Reputation: 6637

A window that uses NSWindowStyleMaskBorderless can’t become key or main, which is why your code doesn't work.

What you could do however is to hide each element of the titlebar instead:

if let window = NSApplication.shared.mainWindow {
    window.standardWindowButton(.closeButton)?.isHidden = true
    window.standardWindowButton(.miniaturizeButton)?.isHidden = true
    window.standardWindowButton(.zoomButton)?.isHidden = true
    window.titleVisibility = .hidden
    window.titlebarAppearsTransparent = true
}

This assumes you only want to change main window. If you want to change all windows, you should loop all windows instead.

Upvotes: 1

Related Questions