I have found several answers on the question how you can set a background image to a UIView in iOS. However I was not able to solve this question for macOS and especially for cocoa. I have tried to set up something like
let bgImage = NSImage(named: "streaks")
let pattern = NSColor(patternImage: bgImage!)
self.view.layer?.background = pattern as! CGColor // this will fail on runtime
Unlike UIView NSView is not layer backed by default, you have to enable it.
self.view.wantsLayer = true
Then create the image and assign it to the contents property of the layer.
let image = NSImage(named: "streaks")
self.view.layer!.contents = image
In Swift 4
self.view.wantsLayer = true
let image = NSImage(named: NSImage.Name(rawValue: "streaks"))
self.view.layer!.contents = image
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With