2

I set background image for the main window of my app inside application delegate:

func applicationDidFinishLaunching(_ aNotification: Notification) {

    if let mw = NSApplication.shared.mainWindow {
        mw.isMovableByWindowBackground = true

        mw.backgroundColor = NSColor.init(red: 0.3, green: 0.3, blue: 0.3, alpha: 1.0)

        if let cv = mw.contentView {
            cv.wantsLayer = true
            let image = NSImage(named: NSImage.Name(rawValue: "bkg"))
            cv.layer!.contents = image
        }
        else {
            print("Content view is not initialized yet")
        }
    }
    else {
        print("Main window is not initialized yet")
    }
}

However, occasionally I see that mainWindow returning nil. So I guess applicationDidFinishLaunching is not the best place to put my code. Also sometimes I notice during app lunch default background appears in the blink of an eye and then background image is applied.

Where is the best place to put my code for applying background image?

Pablo
  • 28,133
  • 34
  • 125
  • 215
  • you sure it's main thread? – Gal Oct 04 '18 at 10:14
  • @Gal at least I don't have any multithreading in my app – Pablo Oct 04 '18 at 13:43
  • `NSApplication.shared.mainWindow`: "The value in this property is nil when the app’s storyboard or nib file has not yet finished loading. It might also be nil when the app is inactive or hidden.". Where/when/how do you create the window? Do you have a reference to the window? Do you use a window controller or view controller? – Willeke Oct 05 '18 at 10:29
  • @Willeke My app is based on Xcode boilerplate for single window app. So window controller is used for main window. It's created off the storyboard. I have no reference to main window and the only place I deal with it is app delegate's `applicationDidFinishLaunching`. Why the window occasionally would be inactive or hidden during launch? – Pablo Oct 06 '18 at 09:04
  • I've now moved background image set routines into `windowDidLoad` of `NSWindowController` inherited class. Not sure if this will solve the problem though. – Pablo Oct 06 '18 at 13:20

0 Answers0