1

I want to update the image when the user clicks something in the application but I can't get it to work. The status item with the menu is defined in the AppDelegate. I am trying to update the image in the ViewController with this piece of code which I think should work:

AppDelegate().statusItem.button?.image = NSImage(named:NSImage.Name("icon-orange"))

No errors are showing up, but turns out it still doesn't work, so is it possible to change the image or am I doing something wrong?

Infiltrator
  • 309
  • 2
  • 13

1 Answers1

2

AppDelegate() creates a brand new instance which is not the delegate class in Interface Builder.

You need the real reference:

(NSApp.delegate as! AppDelegate).statusItem.button?.image = NSImage(named:NSImage.Name("icon-orange"))
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks! Works perfect! Pretty new to swift so maybe it was a dumb question ;) – Infiltrator Jun 27 '18 at 09:38
  • No, it's not. I wish the compiler would show a warning if a class which is designed in Interface Builder is going to be initialized with the default initializer `...()` – vadian Jun 27 '18 at 09:44
  • Is this also possible for getting an already defined class? For example if you have the ViewController class and a Settings class. A variable is defined in the ViewController. Then you want to update from the Settings class the variable in the ViewController class. You don't want to create a new instance, right? So, maybe there is something similar to the solution to get the real delegate? – Infiltrator Jun 27 '18 at 10:09
  • Yes, for classes designed in IB you need always the actual reference. – vadian Jun 27 '18 at 10:15
  • Do you maybe have a small code example of getting the actual reference of an already defined class? Can't find it with a quick Google search... – Infiltrator Jun 27 '18 at 10:19
  • 1
    Sorry that's beyond the scope of this question. Please ask a new one. – vadian Jun 27 '18 at 10:22