Reputation: 921
I want to create an osx/cocoa application on my mac, which does something very simple: Display a text string on my mac, with no background. Ultimately this will be a timer which displays as an overlay on top of other windows, without being too intrusive.
I tried setting window.backgroundColor = NSColor(red: 1.0, green:0.5, blue:0.5, alpha: 0.5)
(see the alpha is 0.5), in applicationDidFinishLaunching
but this doesn't turn it into something remotely transparent.
Any good soul wants to suggest a way to do this?
Upvotes: 24
Views: 20989
Reputation: 517
Here is my updated version of this answer for Swift 5:
import Cocoa
final class CustomWindow: NSWindow {
override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing bufferingType: NSWindow.BackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: style, backing: bufferingType, defer: flag)
isOpaque = false
hasShadow = false
titlebarAppearsTransparent = true
backgroundColor = .clear
title = "Title"
}
}
Upvotes: 0
Reputation: 5229
A little update for Swift 3
A window subclass example with comment:
class customWindow: NSWindow {
override init(contentRect: NSRect, styleMask style: NSWindowStyleMask, backing bufferingType: NSBackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: style, backing: bufferingType, defer: flag)
// Set the opaque value off,remove shadows and fill the window with clear (transparent)
self.isOpaque = false
self.hasShadow = false
self.backgroundColor = NSColor.clear
// Change the title bar appereance
self.title = "My Custom Title"
//self.titleVisibility = .hidden
self.titlebarAppearsTransparent = true
}
Upvotes: 7
Reputation: 236558
NSWindow has a property 'opaque' which it is true by default.
The value of this property is true when the window is opaque; otherwise, false.
Just change it to false:
override func viewWillAppear() {
super.viewWillAppear()
view.window?.opaque = false
view.window?.backgroundColor = NSColor(red: 1, green: 0.5, blue: 0.5, alpha: 0.5)
}
Swift 4 update: opaque
has been renamed isOpaque
override func viewWillAppear() {
super.viewWillAppear()
view.window?.isOpaque = false
view.window?.backgroundColor = NSColor(red: 1, green: 0.5, blue: 0.5, alpha: 0.5)
}
Upvotes: 22
Reputation: 1811
Swift 3/4
self.window?.isOpaque = false
self.window?.hasShadow = false
self.window?.backgroundColor = NSColor.clear
self.window?.titlebarAppearsTransparent = true
Upvotes: 4
Reputation: 6928
Make the window non-opaque, and give it a clear background:
func applicationDidFinishLaunching(aNotification: NSNotification) {
window.opaque = false
window.backgroundColor = NSColor.clearColor()
}
Upvotes: 18