Search code examples
swiftmacosuser-interfaceswiftuiterminology

How to draw a rectangle without a border in Swift (MacOS)


My current code is pretty basic because I'm still new to Swift. However, I can't figure out how to just draw a rectangle on screen without the border(close, minimize, enlarge buttons) like in this picture:

the rectangle as currently drawn

(Also please tell me what that border is actually called!)

import SwiftUI

struct ContentView: View {
    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 200, height: 200)
    }
}

Anyways, I'm used to coding in Lua for Garry's Mod, where I am able to draw the rectangle on-screen anywhere I want by defining the coordinates and size of the rectangle, so I'm just wondering is it possible to do the same on Swift, or perhaps another language would be more beneficial?

Thanks in advance!


Solution

  • Title with buttons is part of window, not drawing rectangle, so you have just create another type of window (without title & buttons), so you your AppDelegate

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()
            .edgesIgnoringSafeArea(.top) // to extend entire content under titlebar 
    
        // Create the window and set the content view. 
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .texturedBackground, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
    
        window.titlebarAppearsTransparent = true // as stated
        window.titleVisibility = .hidden         // no title - all in content
    
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }