I'm new to Swift and Mac App. So I'm writing an Mac App today and I still confuse how to access an IBOutlet from another class after searching a lot.
I'm using StoryBoard and there are two NSTextField path
mirror
in my ViewController.
I have created a custom class Path.swift
for the first NSTextField path
to know when the text in path
has changed.
class Path: NSTextField, NSTextFieldDelegate
{
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
// Drawing code here.
self.delegate = self
}
var current = ""
override func controlTextDidChange(obj: NSNotification)
{
current = self.stringValue
println("Current is \(current)")
}
}
And there are two outlets defined in ViewController.swift
class ViewController: NSViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBOutlet weak var path: NSTextField!
@IBOutlet weak var mirror: NSTextField!
}
And when user type something in the first NSTextField path
, I want the second NSTextField mirror
shows the same string as path
.
I tried to use ViewController().mirror.stringValue = current
, but I got fatal error: unexpectedly found nil while unwrapping an Optional value
After googling a lot, I knew that I have created a new instance of ViewController instead of accessing the current existing instance of ViewController.
So my question is how I can access the IBOutlet in ViewController.swift
from Path.swift
class (how to access the current existing instance of ViewController).
Any help will be greatly appreciated.
Thanks in advance.