This is the second issue in my post "ProgressBar with DispatchQueue", delegation.
I have used delegates with menu items but not program vars.
In the previous post my ViewController has a progress bar but I would like the progress.DoubleValue var to be updated in a remote function, i.e., a function not declared within the ViewController class. (If I moved the function into the ViewController it would double in size.)
How do I create and implement such a delegate? Please give example code. Thanks.
Type is NSProgressIndicator
.
a function not declared within the ViewController class.
Where is it declared ?
- In another VC ? Then see following for delegation.
- If just in another class, but not a VC, call the func as OtherClass.thefunc() - That's not delegation.
You can read this (old) thread with my answer:
https://forums.developer.apple.com/thread/111569
Here is the pattern. This was to update a UITextField but could be adapted to other objects and to AppKit easily.
- You have VC1 and VC2 ; you want to update a field in VC1 when you change a text in VC2.
- Declare a protocol
protocol UpdateVC1 {
func updateName(newName: String)
}
- Declare that VC1 conforms to it, and implement it:
- Set the delegate property of VC2 when you segue
class VC1: UIViewController, UpdateVC1 {
@IBOutlet weak var userNameField: UITextField!
func updateName(newName: String) {
userNameField.text = newName
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? VC2 {
destination.delegate = self
}
}
}
- In VC2 declare a delegate property:
class VC2: UIViewController {
var delegate: UpdateVC1?
- Then, when you change the field with name, invoke the delegate
delegate?.updateName(newName: name)