Access an IBOutlet from another class in Swift

爱⌒轻易说出口 提交于 2019-12-10 16:36:57

问题


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.

来源:https://stackoverflow.com/questions/30909838/access-an-iboutlet-from-another-class-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!