Home > Mobile >  Access to ViewController outlets from AppDelegate
Access to ViewController outlets from AppDelegate

Time:07-25

I created an outlet in ViewController class and I'd like to modify it.
In the ViewController.swift file I have

import Cocoa

class ViewController: NSViewController {
   @IBOutlet var LabelText: NSTextFieldCell?

    override func viewDidLoad() {        
       super.viewDidLoad()
    }
//other things
}

I'd like to change the background color of the label. How can I do that from AppDelegate?
At first I thought I could solve this problem using a function in ViewController and calling it in AppDelegate

func changeBackground() {
    LabelText.textColor = NSColor.red
}

But soon I realised that it wasn't possible unless I used a static function. Then I tried to modify the code in ViewController like that

static func changeBackground() {
    LabelText.textColor = NSColor.red
}

and call this function in AppDelegate like that

ViewController.changeBackground()

In this way I can access to changeBackground() function from AppDelegate, but in ViewController it gives me an error: Instance member 'LabelText' cannot be used on type 'ViewController'

I understood that this cannot be possible because somehow I'm calling "LabelText" before it's initialised (or something like that).
I don't know much about Swift and I'm trying to understand how it works. I've been searching for the answer to my question for hours, but still I don't know how to solve this.

CodePudding user response:

Solution

As Rob suggested, the solution is to use NotificationCenter. A useful link to understand how it works: https://www.appypie.com/notification-center-how-to-swift

Anyway, here how I modified the code.
In ViewController:

class ViewController: NSViewController {

   @IBOutlet var label: NSTextFieldCell!

   let didReceiveData = Notification.Name("didReceiveData")

   override func viewDidLoad() {
      NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: didReceiveData, object: nil)
      super.viewDidLoad()
   }

   @objc func onDidReceiveData(_ notification: Notification) {
      label.textColor = NSColor.red
   }
}

And then, in AppDelegate:

let didReceiveData = Notification.Name("didReceiveData")
NotificationCenter.default.post(name:   didReceiveData, object: nil)
  • Related